JSONObject转换为JSONArray

一.JSONObject转JSONArray

//json串内容如下
{
    "request_id":"1111111111112",
    "audience":["aaa","bbb"],
    "settings":{
        "ttl":36000000,
        "strategy":{
            "default":3,
            "ios":4
        }
    }
}

以com.alibaba.fastjson中的JSONArray与JSONObject为例:

public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "{\n" +
                "    \"request_id\":\"1111111111112\",\n" +
                "    \"audience\":[\"aaa\",\"bbb\"],\n" +
                "    \"settings\":{\n" +
                "        \"ttl\":36000000,\n" +
                "        \"strategy\":{\n" +
                "            \"default\":3,\n" +
                "            \"ios\":4\n" +
                "        }\n" +
                "    }\n" +
                "}";
        //一:JSONObject转JSONArray
        //json字符串转JSONObject
        JSONObject json = JSONObject.parseObject(str); //json = {"settings":{"strategy":{"default":3,"ios":4},"ttl":36000000},"audience":["aaa","bbb"],"request_id":"1111111111112"}
        //方法一: 调用JSONArray的add方法,将JSONObject对象添加到JSONArray中
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(json);
        System.out.println("方法一:"+jsonArray); //jsonArray = [{"settings":{"strategy":{"default":3,"ios":4},"ttl":36000000},"audience":["aaa","bbb"],"request_id":"1111111111112"}]
        //方法二:直接在json前后加上 [] 符号
        String jsonArr = "["+json+"]";
        System.out.println("方法二:"+jsonArr); // jsonArr = [{"settings":{"strategy":{"default":3,"ios":4},"ttl":36000000},"audience":["aaa","bbb"],"request_id":"1111111111112"}]

    }

你可能感兴趣的:(java,json,jsonobject)