JSONObject和JSONArray

一、JSONObject和JSONArray的数据表示形式

JSONObject的数据是用 {  } 来表示的,

        例如:   { "id" : "123", "courseID" : "huangt-test", "title" : "提交作业", "content" : null  }  

而JSONArray,顾名思义是由JSONObject构成的数组,用  [ { } , { } , ......  , { } ]  来表示

       例如:   [ {  "id" : "123", "courseID" : "huangt-test", "title" : "提交作业" }  ,  {  "content" : null, "beginTime" : 1398873600000  "endTime" } ] ; 

        表示了包含2个JSONObject的JSONArray。

可以看到一个很明显的区别,一个用的是 {  }  ,一个最外面用的是 [  ]  ;

取哪个用哪个

1. 如取data以及data下的任意key(同级,不能取data.report下的trackInfo,如果有和report同级的可以取到) (JSONObject {})则为

JSONObject data_action = responseToJson.getJSONObject("data").getJSONObject("action");

2. 如取nodes(JSONArray []) 则为

JSONArray nodes = responseToJson.getJSONArray("nodes");

3. 如取type (String "")则为

String nodes_type = responseToJson.getJSONArray("nodes").getJSONObject(0).getJSONArray("nodes").getJSONObject(0).getString("type");

特殊说明:其实type应该按int类型取,接口返回什么类型就按什么类型取就行,为了保持统一,判断的时候我再转回来

if (Integer.parseInt(nodes_type) != 1054) {

4. 如取level (Integer)则为
Integer nodes_level = responseToJson.getJSONArray("nodes").getJSONObject(0).getJSONArray("nodes").getJSONObject(0).getInteger("level");

5. 如取designate_mode(String "") 则为
String kubox_designate_mode = responseToJson.getJSONObject("data").getJSONObject("action").getJSONObject("report").getJSONObject("trackInfo").getString("designate_mode");

 

package com.alibaba.logPlayBack.sdksearch.searchScene;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.logPlayBack.sdksearch.logDeal.logJoinPrint;

public class default_page {
    /**
     * @param responseToJson
     * @param count          default_page为搜索默认页场景
     */
    public static void parse2JSON(JSONObject requestToJson, JSONObject responseToJson, int count) {

        boolean default_page = requestToJson.getString("appScene").equals("default_page");

        if (default_page) {

            // 取[]是JSONArray,如nodes: [] ,取{}是JSONObject,如data:{},取int类型的返回值是getString,如status: 0
            // 发现在浏览器里的返回key没有"",如level: 0,  在Charles里key有"",如"level": 0,

            /**
             * {
             *     "data": {
             *        "newSearch": 0,
             *        "action": {
             *           "report": {
             *              "trackInfo": {
             *                 "engine": "xx"
             *                                }
             *                    }
             *        },
             *        "status": 0
             *    },
             *     "more": false,
             *     "type": 0,
             *     "nodes": [{
             *        "level": 1,
             *        "more": false,
             *        "type": 0,
             *        "nodes": [{
             *           "data": {
             *                "defaultTab": "xx"
             *                    },
             *             "style": [
             *                   {
             *                      "type": 0
             *                 }
             *            ],
             *            "id": 0
             *          }
             *  ],
             */

            // 1. 返回类型为JSONObject,data: {}
            JSONObject data = responseToJson.getJSONObject("data");
            JSONObject action = responseToJson.getJSONObject("data").getJSONObject("action");
            JSONObject report = responseToJson.getJSONObject("data").getJSONObject("action").getJSONObject("report");
//                System.out.println("report为==" + report);
            String trackInfo = responseToJson.getJSONObject("data").getJSONObject("action").getJSONObject("report").getString("trackInfo");
//                System.out.println("trackInfo为==" + trackInfo);

            if (responseToJson.containsKey("data")) {
                if (data.containsKey("action")) {

                    if (!action.isEmpty()) {
                        if (!report.containsKey("trackInfo")) {
                            System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "不包含trackInfo");
                        }
//                            System.out.println(logJoinPrint.passDesc(requestToJson, count) + "包含trackInfo");

                    } else {
                        System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "data.action为空");
                    }
                } else {
                    System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "不包含action");
                }

                // 2. 返回类型为String,status: 0
                // 多种写法,getString getInteger
//                String data_status = responseToJson.getJSONObject("data").getString("status");
                Integer status = responseToJson.getJSONObject("data").getInteger("status");
//                System.out.println("第" + count + "条日志,status为:" + data_status);
                if (data.containsKey("status")) {
                    if (!String.valueOf(status).isEmpty()) {
//                            System.out.println(logJoinPrint.passDesc(requestToJson, count) + "status不为空");

                        // 如果上面用的是getString,则value取值为String,data_status.equals("0");如果是getInteger,则value取值为String.valueOf,int转换为String;或者直接int类型判断,data_status==0
                        // 因为接口返回为int类型,所以用Integer
//                if (data_status.equals("0")) {
//                if (String.valueOf(data_status).equals("0")) {
                        if (status == 0) {
//                            System.out.println(logJoinPrint.passDesc(requestToJson, count) + "status为0");
                        } else {
                            System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "status不为0");
                        }

                    } else {
                        System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "status为空");
                    }
                } else {
                    System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "不包含status");
                }

                // 3. 返回类型为JSONArray,nodes: [] 数组不可以用
                JSONArray nodes = responseToJson.getJSONArray("nodes");

                // {[{[{{}}],[]}]} 想得到哪个值,用哪个方法取,上面获取到的是[],接下来是[]里的{},再接下来是{}里的[],再再接下来是[]里的{}
                JSONArray nodes_nodes = nodes.getJSONObject(0).getJSONArray("nodes");
                /**
                 * nodes: [
                 *  {
                 *      level: 1,
                 *      more: false,
                 *      type: 0,
                 *      nodes: [
                 *          {
                 *              data: {},
                 *              type: 1041,
                 *              nodes: [],
                 *              style: [],
                 *              id: 0
                 *          }
                 *      ],
                 *      style: [],
                 *      id: 0
                 *  },
                 *  {}
                 */
                // type为[{[{}]}]最内层的JSONObject
                // 如果value是String类型,则用JSONObject就行,如下
//                JSONObject nodes_nodes_type = nodes_nodes.getJSONObject(0).getJSONObject("type");
                // 如果value是int类型,则需要用getInteger或者getString,否则会报错
                String nodes_nodes_type = nodes_nodes.getJSONObject(0).getString("type");
//                System.out.println("第" + count + "条日志,type为:" + nodes_nodes_type);

                if (!nodes_nodes_type.isEmpty()) {
//                    System.out.println(logJoinPrint.passDesc(requestToJson, count) + "nodes_nodes_type数组不为空");
                    // String类型转换为int类型
                    if (Integer.parseInt(nodes_nodes_type) > 1000) {
//                        System.out.println(logJoinPrint.passDesc(requestToJson, count) + "nodes_nodes_type为" + nodes_nodes_type);

                    } else {
                        System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "nodes_nodes_type错误");
                    }
                } else {
                    System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "nodes_nodes_type数组为空");
                }

            }

        }

        System.out.println("搜索场景【mobile_multi】日志回放结束,共" + count + "条日志");


    }
}

运行结果:

 



判断json是否为空,转换为toString()

if (TextUtils.isEmpty(responseToJson.toString())) {

/Users/xx/.m2/repository/com/alibaba/fastjson/1.2.58/fastjson-1.2.58.jar!/com/alibaba/fastjson/JSON.class

public String toString() {
    return this.toJSONString();
}

判断jsonArray数组长度

 

JSONArray duration = data.getJSONObject("filter").getJSONArray("duration");

duration.size();
System.out.println("==duration的长度为"+duration.size());

// JSONArray数组长度,size()方法
if(duration.size()!=5){
    System.err.println(logJoinPrint.bugDesc(requestToJson, count) + "duration.size();筛选项数目错误,不为5");

}

 

解析过程遇到的问题积累

  // 获取value的值
            String value = requestToJson.getString(key);
            value.replace("\\\\", "\\");
//            System.out.println("测试" + value);
            try {
                // "trackInfo":"{"group_id":"xx","object_url":"xx:\/\/xx\/series?title=生死连&showId=xx&siteId=14&keyword=生死连&trackInfoAppend={\"group_num\":1}","object_type":3,"group_num":1,"item_log":"eps_t~1$site~14$show_id~xx$doc_source~1$eng_source~6$sp_id~xx","object_num":1,"source_id":14,"object_title":"查看更多","group_type":1}",
                // "object_url":"xx:\/\/xx\/series?title=生死连&showId=xx&siteId=14&keyword=生死连&trackInfoAppend={\"group_num\":1}"
                
                // 如果为contains的话,value可能在头中尾包含{,中尾部包含{ 但又不是JSONObject,无法解析
//                 if (value.contains("{")) {
                     // 改为startsWith,则不会出现上面的情况
                if (value.startsWith("{")) {
//                    Log.error("lishan==="+value);
                    // [ERROR] lishan===xx://xx/xx?title=琅琊榜&showId=xx&siteId=7&keyword=琅琊榜胡歌版&trackInfoAppend={"group_num":1}
                    // 递归遍历,第一次取到的是外层json,如果value里面还有json,再调用一次。这就是递归遍历
                    requestJsonToMap(JSONObject.parseObject(value), resultMap);
                } else {
                    resultMap.put(key, value);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.error("lishan==="+value);
            }

 

 

修改后的效果:

 

 

待续。。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东方狱兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值