Java中Json转Map方法
Java用JSONObject.toBean进行json字符串转换成Map集合
转换实例一
public void readJSON2Map() {
try {
fail("==============JSON Arry String >>> Java Map ==================");
json = "{\"arr\":[\"a\",\"b\"],\"A\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"-11-22\"}," + "\"email\":\"email\",\"id\":1,\"name\":\"jack\"},\"int\":1," + "\"B\":{\"address\":\"address\",\"birthday\":{\"birthday\":\"-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();
}
}
执行结果:
==============JSON Arry String >>> Java Map ==================
{A=jack#1#address#-11-22#email, arr=[a, b], B=jack#1#address#-11-22#email, int=1, name=json, bool=true}
A:jack#1#address#-11-22#email
arr:[a, b]
B:jack#1#address#-11-22#email
int:1
name:json
bool:true
转换实例二
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");
System.out.println(output2.size());
System.out.println(output2.get("k1"));
}
执行结果:
Map
4
json
[a, b]
Map
2
net.sf.ezmorph.bean.MorphDynaBean@5b8827[{sex=男, age=10, userName=xiapi1}]
版权声明:本文为JAVASCHOOL原创文章,未经本站允许。