欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA处理JSON内容

程序员文章站 2022-07-12 15:11:33
...

该方法适用于百度AI返回的JSON内容处理,其它的还没试过。要想取“score”的值,需要一层一层的剥洋葱,进行多次转换,期间多次用到JSONObject和JSONArray进行抽取,最后一层JSONObject被剥离出来后即可get([String])得到里面的值。

首先通过调用接口返回的JSON值如下:

{
  "result": {
    "face_token": "78108**********7bff19a9c2a24e2",
    "user_list": [{
      "score": 100,
      "group_id": "user",
      "user_id": "吴亦凡",
      "user_info": ""
    }]
  },
  "log_id": 652*****10,
  "error_msg": "SUCCESS",
  "cached": 0,
  "error_code": 0,
  "timestamp": 1628355273
}

花括号”{ }”为一个JSONObject ,中括”[ ]”号为一个数组,数组中又可能会有一个或多个JSONObject。

第一步,根据外层是中括号or花括号做JSON抽取。
JSONObject jsonObject = json.getJSONObject(“result”);
抽取出来后是一个JSONObject,值如下:

{"face_token":"7810845******c2a24e2","user_list":[{"score":100,"group_id":"user","user_id":"吴亦凡","user_info":""}]}

第二步,抽取JSONObject中的第二个对象user_list,因user_list的值是用的中括号,所以抽取出来的内容为数组

JSONArray jsonArray = jsonObject.getJSONArray(“user_list”);
值如下:

[{"score":100,"group_id":"user","user_id":"吴亦凡","user_info":""}]

第三步,抽取出来的值的再下一层又是花括号,所以再次用JSONObject进行抽取,此时数组只有一个

[ 数组0: {“score”:100,”group_id”:”user”,”user_id”:”吴亦凡”,”user_info”:””} ] //忽视中括号,看括号的里层是什么

JSONObject jsonObject1 = jsonArray.getJSONObject(0);
//只有一个数组,所以这里取0位置上的内容,如果有多个根据需要的数据取或者遍历
值如下:

{"score":100,"group_id":"user","user_id":"吴亦凡","user_info":""}

第四步,此时抽取出来的最后一层为JSONObject,因此可以直接使用 get( [String] )方法取目标对象的值

 Object score = jsonObject1.get("score"); 
        //返回值类型在变,int F  D 所以用OBJ才行,拿到值再做转换
        
        try {
            if (score instanceof Float) {
                Float result = (float) score;
                return result;
            } else if (score instanceof Double) {
                Double result = (Double) score;
                return result;
            } else if (score instanceof Integer) {
                Integer result = (Integer) score;
                return result;
            } else if (score instanceof Boolean) {
                Boolean result = (Boolean) score;
                return result;
            } else if (null == score) {
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //输出JSON所有内容
            System.out.println(json.toString(2));
        }
        return false;

小结:JSON返回值,多层嵌套且类型不一样,需要对不同类型的层级做多次与之相匹配的类型抽取才能拿到想要的目标值。

对识别结果进行判断:

 public boolean isOrNot(){
        if (JsonUtil.getJson(getCompareResults()) instanceof Float
                || JsonUtil.getJson(getCompareResults()) instanceof Double
                || JsonUtil.getJson(getCompareResults()) instanceof Integer ) {

            Object resultStr = JsonUtil.getJson(getCompareResults());
            Double result = Double.valueOf(resultStr.toString());
            log.info(resultStr);
            if (result >60D){
                return true;
            }
        } else if (JsonUtil.getJson(getCompareResults()) instanceof Boolean) {
            Boolean result = (Boolean) JsonUtil.getJson(getCompareResults());
            return result;
        } else if (null == JsonUtil.getJson(getCompareResults())) {
            //TODO 空指针异常处理 暂时返回false
            return false;
        }
        return false;
    }

测试码:

@Test
    public void localimagetest() {
        String imageTypes = "BASE64";
        IO io = new IOImpl();
        io.setLocalimage("C:\\Users\\username\\Downloads\\wu\\wu.jpg");

        ImageToBase64 imageToBase64 = new ImageToBase64Util();
        imageToBase64.setBase64(io.getLocalImage());
        String imageres = imageToBase64.getBase64();
        UserImage userImage = new UserImage("*fang","user",imageres);
        UserData userData = new UserFaceData(userImage);
        BaiduApiJudge baiduApiJudge = new BaiduApiJudge();
        baiduApiJudge.faceSearch(userData,imageTypes);
        Boolean compareResult = baiduApiJudge.isOrNot();
        if (!compareResult){
            log.info(Judges.ISNOT.getJudges());
        }else {
            log.info(Judges.IS.getJudges());
        }
    }
    @Test
    public void netimagetest() throws MalformedURLException {
        String imageTypes = "BASE64";
        IO io = new IOImpl();
        URL url = new URL("https://i0.wp.com/www.hellokpop.com/wp-content/uploads/2014/08/Kris-3-kris-35588094-1500-1000.jpg?fit=1500%2C1000&ssl=1");
        io.setNetimage(url);

        ImageToBase64 imageToBase64 = new ImageToBase64Util();
        imageToBase64.setBase64(io.getNetImage());
        String imageres = imageToBase64.getBase64();

        UserImage userImage = new UserImage("*fang","user",imageres);
        UserData userData = new UserFaceData(userImage);
        BaiduApiJudge baiduApiJudge = new BaiduApiJudge();
        baiduApiJudge.faceSearch(userData,imageTypes);
        Boolean compareResult = baiduApiJudge.isOrNot();
        if (!compareResult){
            log.info(Judges.ISNOT.getJudges());
        }else {
            log.info(Judges.IS.getJudges());
        }


    }
    @Test
    public void imageurl() {
        String imageTypes = "URL";
        IO io = new IOImpl();
        String url = "http://www.abc.com/upload/30a1a15797e4469a93fd278fae292af.jpg";
        io.setLocalimage(url);
        String imageres = io.getLocalImage();
        UserImage userImage = new UserImage("wuqian","user",imageres);
        UserData userData = new UserFaceData(userImage);
        BaiduApiJudge baiduApiJudge = new BaiduApiJudge();
        baiduApiJudge.faceSearch(userData,imageTypes);
        Boolean compareResult = baiduApiJudge.isOrNot();
        if (!compareResult){
            log.info(Judges.ISNOT.getJudges());
        }else {
            log.info(Judges.IS.getJudges());
        }
    }