java构建一个格式稍微复杂点的JSON对象附查看json格式的小工具

来源:互联网 发布:电脑硬盘坏了恢复数据 编辑:程序博客网 时间:2024/05/22 06:40

调用第三方接口时经常要按照约束文档构建各种格式的JSON对象

构建一个格式稍微复杂点的JSON对象对象里边包含普通键值对、数组、对象等{    "total": "1",    "hits": [        {            "id": ".watcher-history-3-2017.09.7",            "index": "logstash",            "jsaInnerJso": {                "message": "测试数据查看返回值",                "hostIP": "22.5.254.175"            }        }    ]}
public class CreatJSONObject {    /**     *      *  {            "total": "1",            "hits": [                {                    "id": ".watcher-history-3-2017.09.7",                    "index": "logstash",                    "jsaInnerJso": {                        "message": "测试数据查看返回值",                        "hostIP": "22.5.254.175"                    }                }            ]        }     */    public static JSONObject createJSONObject(){        //最外层的JSON对象        JSONObject jso = new JSONObject();        jso.put("total", "1");        //hits的值是一个数组        JSONArray jsa = new JSONArray();        //数组里边装着个对象        JSONObject jsaInnerJso = new JSONObject();        jsaInnerJso.put("id", ".watcher-history-3-2017.09.7");        jsaInnerJso.put("index", "logstash");        //数组里边对象的source元素的值也是一个对象        JSONObject jsaInner_inner_JsoValue = new JSONObject();        jsaInner_inner_JsoValue.put("hostIP","22.5.254.175");        jsaInner_inner_JsoValue.put("message", "测试数据查看返回值");        //不数组里边对象的source元素添加进去        jsaInnerJso.put("jsaInnerJso", jsaInner_inner_JsoValue);        //将数组里边的对象添加进数组        jsa.add(jsaInnerJso);        //最外层的JSON对象添加hits元素        jso.put("hits", jsa);        //搞定        return jso;    }    //测试一下    public static void main(String[] args) {        System.out.println(createJSONObject());    }

结果:

{"total":"1","hits":[{"id":".watcher-history-3-2017.09.7","index":"logstash","jsaInnerJso":{"message":"测试数据查看返回值","hostIP":"22.5.254.175"}}]}

附:参看json格式的小工具:http://download.csdn.net/download/leisure_life/9967682

这里写图片描述

这里写图片描述