生成复杂json和解析

@Test
    public void test8() {
        com.google.gson.JsonObject jsonObjectDad = new com.google.gson.JsonObject();//父级json
        com.google.gson.JsonObject jsonObjectSon = new com.google.gson.JsonObject();//子级json
        com.google.gson.JsonArray jsonElementDad = new com.google.gson.JsonArray();//父级数组
        com.google.gson.JsonObject jsonObjectArraySon = new com.google.gson.JsonObject();//数组里具体的子级json
        ArrayList<String> list = new ArrayList<>();
        //拼接子级json
        jsonObjectSon.addProperty("ErrorCode", 0);
        jsonObjectSon.addProperty("Message", "null");
        jsonObjectSon.addProperty("Success", "true");
        jsonObjectSon.addProperty("Result", "null");
        //将子级json添加到父级json中
        jsonObjectDad.add("status", jsonObjectSon);

        for (int i = 0; i < 2; i++) {
            //构建数组里的具体的子级json
            jsonObjectArraySon.addProperty("OrderId", "30141275017");
            jsonObjectArraySon.addProperty("OrderType", 4);
            //添加到父级数组中
            jsonElementDad.add(jsonObjectArraySon);
        }

        //父级数组添加到父级json中,完成构建复杂json
        jsonObjectDad.add("datas", jsonElementDad);
        System.out.println(jsonObjectDad.toString());


        //解析返回值
        String HotelOrder = jsonObjectDad.toString();
        com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSON.parseObject(HotelOrder);
        //
        Object status = result.get("status");
        com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSON.parseObject(status.toString());
        Object success = jsonObject1.get("Success");
        if ("true".equals(success.toString())) {
            Object datas = result.get("datas");
            com.alibaba.fastjson.JSONArray jsonArray = com.alibaba.fastjson.JSONObject.parseArray(datas.toString());
            for (int i = 0; i < jsonArray.size(); i++) {
                Object o = jsonArray.get(i);
                Object orderId = com.alibaba.fastjson.JSON.parseObject(o.toString()).get("OrderId");

                list.add(orderId.toString());
                System.out.println("便便:"+list);
            }
        }


    }

生成的json:

{
    "status": {
        "ErrorCode": 0,
        "Message": "null",
        "Success": "true",
        "Result": "null"
    },
    "datas": [
        {
            "OrderId": "30141275017",
            "OrderType": 4
        },
        {
            "OrderId": "30141275017",
            "OrderType": 4
        }
    ]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容