//将map数据转化为json数据
JSONObject json = new JSONObject();
Iterator<Map.Entry<String, TbTrackScaleReceiveDepartment>> entries =
tbTrackScaleReceiveDepartmentMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, TbTrackScaleReceiveDepartment> entry = entries.next();
json.put(entry.getKey(),entry.getValue());
}
System.out.println(json.toString());
Java中Json转Map方法
public void readJSON2Map() {
try {
fail("==============JSON Arry String >>> Java Map ==================");
json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1," + "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"2010-11-22\"}," + "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"name\":\"json\",\"bool\":true}";
jsonObject = JSONObject.fromObject(json);
Map < String,Class < ?>>clazzMap = new HashMap < String, Class < ?>>();
clazzMap.put("arr", String[].class);
clazzMap.put("A", Student.class);
clazzMap.put("B", Student.class);
Map < String,?>mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);
System.out.println(mapBean);
Set < String > set = mapBean.keySet();
Iterator < String > iter = set.iterator();
while (iter.hasNext()) {
String key = iter.next();
fail(key + ":" + mapBean.get(key).toString());
}
} catch(Exception e) {
e.printStackTrace();
}
}
public void json2map() {
String json1 = "{'arr':['a','b'],'int':1,'name':'json','bool':true}";
JSONObject jsonObject1 = JSONObject.fromObject(json1);
Map typeMap1 = new HashMap();
typeMap1.put("arr", String[].class);
typeMap1.put("int", Integer.class);
typeMap1.put("name", String.class);
typeMap1.put("bool", Boolean.class);
Map output1 = (Map) JSONObject.toBean(jsonObject1, Map.class, typeMap1);
System.out.println("Map");
System.out.println(output1.size());
System.out.println(output1.get("name"));
System.out.println(output1.get("arr"));
String json2 = "{'k1':{'age':10,'sex':'男','userName':'xiapi1'},'k2':{'age':12,'sex':'女','userName':'xiapi2'}}";
JSONObject jsonObject2 = JSONObject.fromObject(json2);
Map < String,Class < ?>>typeMap2 = new HashMap < String,Class < ?>>();
Map < String,Student > output2 = (Map < String, Student > ) JSONObject.toBean(jsonObject2, Map.class, typeMap2);
System.out.println("Map<String,Student>");
System.out.println(output2.size());
System.out.println(output2.get("k1"));
}