1.序列化
即将javabean、map、list等转化为json字符串
(1)JavaBean序列化
@Test
public void test()
{
Person person = new Person();
person.setAge(2);
person.setId(1);
person.setName("lucy");
String jsonString = JSON.toJSONString(person);
System.out.println(jsonString);
}
结果为:
{"age":2,"friend":[],"id":1,"name":"lucy"}
(2)Map序列化
@Test
public void testMap()
{
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("username", "zhangsan");
map.put("age", 24);
map.put("sex", "男");
// map集合
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("name", "xiaohong");
temp.put("age", "23");
map.put("girlInfo", temp);
// list集合
List<String> list = new ArrayList<String>();
list.add("爬山");
list.add("骑车");
list.add("旅游");
map.put("hobby", list);
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);
}
结果为:
{"sex":"男","username":"zhangsan","age":24,"hobby":["爬山","骑车","旅游"],"girlInfo":{"age":"23","name":"xiaohong"}}
2.反序列化
即将json字符串转化为JavaBean、map、list等
(1)转化为JavaBean
@Test
public void testParse()
{
String json="{\"age\":2,\"id\":1,\"name\":\"lucy\"}";
//反序列化
Person personInfo=JSON.parseObject(json,Person.class);
System.out.println("name:"+personInfo.getName()+", age:"+personInfo.getAge());
}
结果为:
name:lucy, age:2
(2)转化为Map
@Test
public void testParse()
{
String json="{\"sex\":\"男\",\"username\":\"zhangsan\",\"age\":24,\"hobby\":[\"爬山\",\"骑车\",\"旅游\"],\"girlInfo\":{\"age\":\"23\",\"name\":\"xiaohong\"}}";
Map<String, Object> map = JSON.parseObject(json, Map.class);
for (Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
结果为:
username zhangsan
sex 男
age 24
hobby ["爬山","骑车","旅游"]
girlInfo {"name":"xiaohong","age":"23"}
(3)获取稍复杂json中的指定数组
{
"count":123,
"result":{
"code":"200",
"status":"success"
},
"list":[
{
"entName":"x",
"entType":"9910",
"speCause":"3",
"abnTime":"Mar 13, 2015 12:00:00 AM"
},
{
"entName":"y",
"entType":"9990",
"speCause":"1",
"abnTime":"Mar 13, 2015 12:00:00 AM"
}]
}
需要获取其中的list来解析:
@Test
public void test() {
JSONObject jObject = JSON.parseObject(rawJson);
JSONArray jArray = jObject.getJSONArray("list");
for (Object object : jArray) {
System.out.println(object);
}
}
结果为:
{"speCause":"3","entType":"9910","entName":"x","abnTime":"Mar 13, 2015 12:00:00 AM"}
{"speCause":"1","entType":"9990","entName":"y","abnTime":"Mar 13, 2015 12:00:00 AM"}
这样获得的就是简单json了,简单转换即可
(4)泛型的反序列化
@Test
public void test4()
{
String json = "{\"person\":{\"name\":\"zhangsan\",\"age\":25}}";
Map<String, Person> map = JSON.parseObject(json,new TypeReference<Map<String, Person>>() {});
for (Entry<String, Person> entry : map.entrySet())
{
System.out.println(entry.getKey()+" "+entry.getValue().getName());
}
}
结果为:
person zhangsan