JackSon介绍
本文使用的JackSon版本为2.9.6。
JackSon是解析JSON和XML的一个框架,优点是简单易用,性能较高。
JackSon处理JSON的方式
JackSon提供了三种JSON的处理方式。分别是数据绑定,树模型,流式API。下面会分别介绍这三种方式。
完整数据绑定
/**
* 下面是最常用的场景,将json字符串映射为对象,或者是将对象转化为json字符串。这是完整数据绑定。
缺点:这种方法十分方便,但是扩展性不强,增加一个字段便要修改POJO对象,这个操作有一定风险性。并且解析的时候,如果json缺少POJO中的某字段,映射出的对象对应值默认为null,直接使用有一定风险。如果json对象多了某一字段,解析过程中会抛出UnrecognizedPropertyException异常。并且如果json较为复杂的话,POJO对象会显得特别臃肿。
*/
public class CompleteDataBind {
public static void main(String[] args) throws IOException {
String s = "{\"id\": 1,\"name\": \"小明\",\"array\": [\"1\", \"2\"]}";
ObjectMapper mapper = new ObjectMapper();
//Json映射为对象
Student student = mapper.readValue(s, Student.class);
//对象转化为Json
String json = mapper.writeValueAsString(student);
System.out.println(json);
System.out.println(student.toString());
}
}
简单数据绑定
简单数据绑定就是将json字符串映射为java核心的数据类型。
json类型 |
Java类型 |
object |
LinkedHashMap |
array |
ArrayList |
string |
String |
number |
Integer,Long,Double |
true|false |
Boolean |
null |
null |
下面演示一个例子,将json转化为一个Map。通过Map来读取。
/**
*
* 简单数据绑定的示例,不用POJO对象,直接映射为一个Map,然后从Map中获取。
*/
public class SimpleDataBind {
public static void main(String[] args) throws IOException {
Map<String, Object> map = new HashMap<>(16);
String s = "{\"id\": 1,\"name\": \"小明\",\"array\": [\"1\", \"2\"]," +
"\"test\":\"I'm test\",\"base\": {\"major\": \"物联网\",\"class\": \"3\"}}";
ObjectMapper mapper = new ObjectMapper();
map = mapper.readValue(s, map.getClass());
//获取id
Integer studentId = (Integer) map.get("id");
System.out.println(studentId);
//获取数据
ArrayList list = (ArrayList) map.get("array");
System.out.println(Arrays.toString(list.toArray()));
//新增加的字段可以很方便的处理
String test = (String) map.get("test");
System.out.println(test);
//不存在的返回null
String notExist = (String) map.get("notExist");
System.out.println(notExist);
//嵌套的对象获取
Map base = (Map) map.get("base");
String major = (String) base.get("major");
System.out.println(major);
}
}
JackSon的常用注解
JackSon提供了一些的注解,可以用在类上或者是在字段上。通常是数据绑定的时候使用。下面几个是最常用的几个
@JsonInclude(Include.NON_EMPTY)
仅在属性不为空时序列化此字段,对于字符串,即null或空字符串
@JsonIgnore
序列化时忽略此字段
@JsonProperty(value = “user_name”)
指定序列化时的字段名,默认使用属性名
总结
JackSon使用起来还是十分方便的,提供的功能也很多,在使用的时候,需要结合自己的业务场景,选择合适的解析方式。