Fastjson和jackson序列化和反序列化Json
先上实体类:
public class People {
String name;
Integer age;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "People [name=" + name + ", age=" + age + "]";
}
}
fastjson:
//fastjson
@Test
public void testFastjson() {
People p = new People();
p.setName("zhangsan");
p.setAge(18);
// 对象转json
String jsonStr = JSONObject.toJSONString(p); // {"age":18,"name":"zhangsan"}
// json转对象
People people = JSONObject.parseObject(jsonStr, People.class); // People [name=zhangsan, age=18]
}
jackson:
//jackson objectMapper
@Test
public void testJackson() throws Exception {
People p = new People();
p.setName("lisi");
p.setAge(81);
// objectMapper是jackson的核心类,基本所有的操作都由它来实现
ObjectMapper om = new ObjectMapper();
// 对象转json
String jsonStr = om.writeValueAsString(p); //{"name":"lisi","age":81}
// json转对象
People people = om.readValue(jsonStr, People.class); //People [name=lisi, age=81]
}
还没有评论,来说两句吧...