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