JSON-lib的api的使用

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了。

posted @ 2014-02-08 11:26  google4y  阅读(404)  评论(0编辑  收藏  举报
不在家,就在公司,不在公司,就在去公司的路上,無家無根,如風如萍,只有漂