JSON-lib的api的使用

google4y發表於2014-02-08
List<Object> list = new ArrayList<Object>();
        Map<String,Object> map1  = new HashMap<String,Object>();
        map1.put("name", "黑龍江");
        JSONObject put = new JSONObject();
        put.put("city", new String[]{"哈爾濱","大慶"});
        map1.put("cities", put.toString());
        list.add(map1);
        
        Map<String,Object> t = new HashMap<String,Object>();
        t.put("name","中國");
        t.put("province", JSONArray.fromObject(list).toString());
        JSONObject j = new JSONObject();
        j.putAll(t);
        System.out.println(j.toString());
{
        "name":"中國",
        "province":[
        {
           "name":"黑龍江",
            "cities":{
                "city":["哈爾濱","大慶"]
            }
         },
         {
            "name":"廣東",
            "cities":{
                "city":["廣州","深圳","珠海"]
            }
        },
        {
            "name":"臺灣",
            "cities":{
                "city":["臺北","高雄"]
            }
        },
        {
            "name":"新疆",
            "cities":{
                "city":["烏魯木齊"]
            }
        }
    ]
    }
// 此範例的另外一種寫法。沒有用List來裝集合,而是用JSONArray

Map<String,Object> map1 = new HashMap<String,Object>(); map1.put("name", "黑龍江"); JSONObject put = new JSONObject(); put.put("city", new String[]{"哈爾濱","大慶"}); map1.put("cities", put.toString()); Map<String,Object> map2 = new HashMap<String,Object>(); map2.put("name", "廣東"); JSONObject put2 = new JSONObject(); put2.put("city", new String[]{"廣州","深圳","珠海"}); map2.put("cities", put.toString()); Map<String,Object> t = new HashMap<String,Object>(); t.put("name","中國"); JSONArray array = new JSONArray(); array.add(map1); array.add(map2); t.put("province", array.toString()); JSONObject j = new JSONObject(); j.putAll(t); j.element("description", "這是描述"); System.out.println(j.toString());

 

能用map來啟用key跟value的話,一般都不用再啟用一個javabean了。

相關文章