目录html
网上有不少关于jackson和json的介绍和使用,我就不重复造轮子了,本篇博客主要介绍jackson的高级应用和博主我本身踩坑心得。java
若是对json和jackson不熟悉的朋友,能够看下面两篇博客。git
https://www.runoob.com/json/json-tutorial.html JSON教程github
https://blog.csdn.net/u011054333/article/details/80504154#commentBox jackson快速入门json
这个注解很是有用,看下面代码:数组
public class Person { @JsonProperty("username") private String name; private Integer age; //省略getter setter }
@Test public void test1() throws Exception{ ObjectMapper mapper = new ObjectMapper(); Person person = new Person("adai",21); System.out.println(mapper.writeValueAsString(person)); }
输出为 {"age":21,"username":"adai"}
app
能够看到,在序列化的json串中,username替代了nameide
public class Person { @JsonIgnore private String name; private Integer age; //省略getter setter }
@Test public void test1() throws Exception{ ObjectMapper mapper = new ObjectMapper(); Person person = new Person("adai",21); System.out.println(mapper.writeValueAsString(person)); }
输出为 {"age":21}
学习
①这个注解和@JsonIgnore有些相似,不过主要是做用在类上面jsonp
@JsonIgnoreProperties(value = {"name","age"}) public class Person { private String name; private Integer age; private Double height; //省略getter setter }
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); Person person = new Person("adai", 21, 172D); String json = mapper.writeValueAsString(person); System.out.println(json); }
输出为 {"height":172.0}
能够看出@JsonIgnoreProperties(value = {"name","age"}) 忽略了name和age属性,在序列化的时候,会忽略这两个属性
②@JsonIgnoreProperties注解还有一个ignoreUnknown属性,主要用在反序列化上
在正常状况下,若是咱们json串中有一些key值和咱们的POJO对象不匹配,那么将会抛出异常。
@Test public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.readValue(" {\"name\":\"adai\",\"age\":21,\"height222\":172.0}", Person.class)); // !!注意height222与咱们的pojo对象不匹配 }
程序将会抛出异常
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "height222" (class com.antiy.common.adai.demo.Person), not marked as ignorable (3 known properties: "name", "age", "height"]) at [Source: (String)"{"name":"adai","age":21,"height222":172.0}"; line: 1, column: 42] (through reference chain: com.antiy.common.adai.demo.Person["height222"])
此时若是咱们在Person类上加上@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIgnoreProperties(ignoreUnknown = true) public class Person { private String name; private Integer age; private Double height; //省略getter setter }
输出为 Person(name=adai, age=21, height=null)
③使用 mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 也能够达到一样的目的
④建议:ignoreUnknown和FAIL_ON_UNKNOWN_PROPERTIES尽可能不要设置为true,若是反序列化的时候,json串中的相关key和POJO属性不匹配,就让程序抛出异常,即便发现错误,不过具体状况还须要参考具体业务,jackson默认该值为false
主要做用:在json串中又包装了一层
①正常状况下,序列化的字符串是 {"name":"adai","age":21,"height":172.0}
当咱们在Person
类上加上@@JsonTypeName和@JsonTypeInfo时
@JsonTypeName(value = "user222") @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) public class Person { private String name; private Integer age; private Double height; //省略getter setter }
输出为 {"user222":{"name":"adai","age":21,"height":172.0}}
②咱们也可使用@JsonRootName("user222")和mapper.enable(SerializationFeature.WRAP_ROOT_VALUE)来达到一样的效果
@JsonRootName("user222") public class Person { private String name; private Integer age; private Double height; //省略getter setter }
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); Person person = new Person("adai", 21, 172D); System.out.println(mapper.writeValueAsString(person)); }
输出为 {"user222":{"name":"adai","age":21,"height":172.0}}
主要用在Date属性上
public class Person { private String name; private Integer age; private Double height; private Date date; //省略getter setter }
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); Person person = new Person("adai", 21, 172D,new Date()); System.out.println(mapper.writeValueAsString(person)); }
输出为 {"name":"adai","age":21,"height":172.0,"date":1558842751645}
注意:jackson默认会将Date类型序列化成时间戳,这是由于SerializationFeature中的WRITE_DATES_AS_TIMESTAMPS(true),
该值默认为true,当咱们手动将改值设为false时。
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
输出为 {"name":"adai","age":21,"height":172.0,"date":"2019-05-26T03:56:38.660+0000"}
这时候date就再也不是时间戳了,可是和咱们中国的时间格式有一些差异,这个时候就可使用@JsonFormat
public class Person { private String name; private Integer age; private Double height; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss:SSS",timezone="GMT+8") private Date date; //省略getter setter }
输出为 {"name":"adai","age":21,"height":172.0,"date":"2019-05-26 11:58:07:296"}
该注解主要用在序列化:
1.方法是非静态,没有参数的,方法名随意
2.方法返回值必须是Map类型
3.在一个实体类中仅仅用在一个方法上
4.序列化的时候json字段的key就是返回Map的key,value就是Map的value
public class Person { private String name; private Integer age; private Map<String, Object> map = new HashMap<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @JsonAnyGetter // 注意这个注解 public Map<String, Object> getOther(){ return map; } }
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); Person person = new Person(); person.setName("adai"); person.setAge(21); Map<String, Object> other = person.getOther(); other.put("city", "chengdu"); System.out.println(mapper.writeValueAsString(person)); }
输出为 {"name":"adai","age":21,"city":"chengdu"}
当咱们在public Map<String, Object> getOther()
上去掉@JsonAnyGetter
这个注解的时候
输出为 {"name":"adai","age":21,"other":{"city":"chengdu"}}
能够看出加上这个注解之后序列化的时候就会将Map里面的值也至关于实体类里面的字段给显示出来了。
主要做用于反序列化上
1.用在非静态方法上,注解的方法必须有两个参数,第一个是json字段中的key,第二个是value,方法名随意
2.反序列化的时候将对应不上的字段所有放到Map里面
public class Person { private String name; private Integer age; private Map<String, String> map = new HashMap<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @JsonAnySetter //注意这个注解 public void setOther(String key, String value){ this.map.put(key, value); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", map=" + map + '}'; } }
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = "{\"name\":\"adai\",\"age\":21,\"color\":\"red\",\"city\":12}"; Person person = mapper.readValue(json, Person.class); System.out.println(person); }
输出为 Person{name='adai', age=21, map={color=red, city=12}}
能够看出,使用@JsonAnySetter注解,在json串中多余的属性会被自动放在map属性中,而不会抛出UnrecognizedPropertyException异常
注意:若是是Map<String,String> 那么即便是 {"name":"adai","age":21,"city":12,"weather":true}
中的city对应数值 12
和weather对应布尔 true
也会被封装进Map<String, String>中,可是Map<String, Integer> 没法封装String或其余类型,只能封装Integer
Java中 List和Map主要和泛型打交道,咱们重点以这两个为例子,来学习jackson中如何在反序列中保留泛型信息的。
public class Student { private String name; private Integer age; //省略getter setter }
@Test public void test3() throws Exception { ObjectMapper mapper = new ObjectMapper(); List<Student> list = new ArrayList<>(); list.add(new Student("adai",21)); list.add(new Student("apei",22)); String json = mapper.writeValueAsString(list); List<Student> student = mapper.readValue(json, List.class); System.out.println(student.get(0).getName()); }
该程序在编译期不会报错,能够执行。那么在运行期的时候能够经过吗?
答案是:否认的。 即程序运行失败
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.antiy.common.adai.demo.Student
缘由①:由于在反序列化的时候,mapper.readValue(json, List.class)
并无告诉jackson,这个json数据能够封装成Student对象,因此jackson默认将[{"name":"adai","age":21},{"name":"apei","age":22}]
封装成两个LinkedHashMap对象,而后放入到List集合中。
缘由②:既然咱们知道了List中保存的对象在运行期是LinkedHashMap,那么为何在代码中还能够student.get(0).getName()
,这就跟Java编译期的泛型擦除有关系了,咱们能够看下反编译后的代码
List<Student> student = (List)mapper.readValue(json, List.class); System.out.println(((Student)student.get(0)).getName());
student.get(0)实际上的对象是LinkedHashMap,而后强转成Student,天然就报错了!
咱们可使用JavaType
来保存泛型信息
List:
@Test public void test4() throws Exception { ObjectMapper mapper = new ObjectMapper(); JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Student.class); List<Student> list = new ArrayList<>(); list.add(new Student("adai",21)); list.add(new Student("apei",22)); String json = mapper.writeValueAsString(list); List<Student> student2 = mapper.readValue(json, javaType); System.out.println(student2.get(0).getName()); }
输出为 adai
Map:
@Test public void test5() throws Exception { ObjectMapper mapper = new ObjectMapper(); JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, String.class, Student.class); // 第二个参数是Map的key,第三个参数是Map的value Map<String, Student> map = new HashMap<>(); map.put("first",new Student("adai",21)); map.put("second",new Student("apei",22)); String json = mapper.writeValueAsString(map); Map<String, Student> result = mapper.readValue(json, javaType); System.out.println(result.get("first").getName()); }
输出为 adai
TypeReference
比javaType
模式更加方便,代码也更加简洁
List:
@Test public void test6() throws Exception { ObjectMapper mapper = new ObjectMapper(); List<Student> list = new ArrayList<>(); list.add(new Student("adai",21)); list.add(new Student("apei",22)); String json = mapper.writeValueAsString(list); List<Student> student2 = mapper.readValue(json, new TypeReference<List<Student>>(){}); System.out.println(student2.get(0).getName()); }
输出为 adai
Map:
@Test public void test7() throws Exception { ObjectMapper mapper = new ObjectMapper(); Map<String, Student> map = new HashMap<>(); map.put("first",new Student("adai",21)); map.put("second",new Student("apei",22)); String json = mapper.writeValueAsString(map); Map<String, Student> result = mapper.readValue(json, new TypeReference<Map<String,Student>>(){}); System.out.println(result.get("first").getName()); }
输出为 adai
能够看到,使用TypeReference
,只须要在mapper.readValue后面增长一个 new TypeReference
匿名内部类,写上本身想要封装的泛型对象,比javaType
少了一行mapper.getTypeFactory().constructParametricType
声明
jackson能够经过SerializationFeature
和DeserializationFeature
来自定义,序列化和反序列化规则,这也是jackson很是强大的地方。
请看下面一个例子:
mapper.configure(SerializationFeature.INDENT_OUTPUT,true); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.disable(SerializationFeature.INDENT_OUTPUT);
这里有三个方法,configure方法接受配置名和要设置的值,Jackson 2.5版本新加的enable和disable方法则直接启用和禁用相应属性,我推荐使用后面两个方法。
默认为false,该属性主要是美化json输出
普通序列化的json串:
{"name":"adai","age":21}
开启该属性后的json串:
{ "name" : "adai", "age" : 21 }
默认为true,该属性的意思是,若是一个对象中没有任何的属性,那么在序列化的时候就会报错
public class Teacher {}
@Test public void test1() throws Exception { ObjectMapper mapper = new ObjectMapper(); Teacher teacher = new Teacher(); System.out.println(mapper.writeValueAsString(teacher)); }
程序运行将会报错:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.antiy.common.adai.entity.Teacher and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
当咱们进行设置: mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
输出为 {}
默认为true,该属性的意思是,jackson默认会将Date类型的数据序列化成时间戳
详情能够参考 2.5 @JsonFormat
默认为true,该属性的意思是,在反序列的时候,若是json串中存在一些key,可是在POJO中没有,那么程序将会抛出异常
@Test public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); Student student = new Student("adai",21); String json = "{\"name\":\"adai\",\"age222\":21}"; //Student中没有age222 mapper.readValue(json,Student.class); }
程序将会报错:UnrecognizedPropertyException: Unrecognized field "age222"
此时咱们将FAIL_ON_UNKNOWN_PROPERTIES
设置为false
public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Student student = new Student("adai",21); String json = "{\"name\":\"adai\",\"age222\":21}"; System.out.println(mapper.readValue(json, Student.class)); }
输出为 Student(name=adai, age=null)
该值默认为false,该属性的意思是,容许JSON空字符串值(“”)做为null绑定到POJO的属性上,看代码可能比较好理解一点。
public class Teacher { private Student student; // 省略 getter setter constructor }
@Test public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = "{\"student\":\"\"}"; System.out.println(mapper.readValue(json, Teacher.class)); }
程序将会报错,MismatchedInputException
,由于json串中key值student对应的value为 ""
此时咱们能够设置DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
为true
输出为 Teacher(student=null)
"" 空串 被转换成null值 封装到Teacher对象的student属性中
默认为false,该属性的意思是,将内容包裹为一个JSON属性,属性名由@JsonRootName注解指定。
详情请见 2.4 @JsonTypeName和@JsonTypeInfo
必定要导入正确的TypeReference
类
注意,该属性只接受POJO的 “” 空字符串转换成 null,在json中,String很是特殊。
请先看4.6章节的内容。
此时我将Teacher中的student类型,换成String
public class Teacher { private String student; }
@Test public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); String json = "{\"student\":\"\"}"; System.out.println(mapper.readValue(json, Teacher.class)); }
输出为 Teacher(student=)
原来觉得,若是是String属性,那么""也会转换成null,结果偏偏相反,只有POJO对象,“”才会转换成null
参考 stackoverflow:https://stackoverflow.com/questions/22688713/jackson-objectmapper-deserializationconfig-feature-accept-empty-string-as-null-o
在对象序列化和反序列化的过程当中,本身对Map和List又有了新的理解。
Map能够当作是一个任意对象,保存字段属性。
在 3.1中,若是jackson不知道反序列化的对象,那么jackson将会以LinkedHashMap来进行处理,这正是由于Map的 Key-Value 特性。
@Test public void test2() throws Exception { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<>(2); map.put("name","adai"); map.put("age",21); System.out.println("map序列化: " + mapper.writeValueAsString(map)); Student student = new Student("adai",21); System.out.println("student序列化: " + mapper.writeValueAsString(student)); }
输出为 map序列化: {"name":"adai","age":21}
student序列化: {"name":"adai","age":21}
能够看到Map和Student序列化的结果都是同样的,那么在反序列化的时候,能够用Student对象接受的数据,天然而然也能够用Map接收,这就是为何在关于泛型反序列化的时候,若是jackson不知道具体的对象,所有都会用LinkHashMap接收
List就当作是一个数组
参考资料:
https://github.com/FasterXML/jackson/
http://www.javashuo.com/article/p-zbvvzltn-a.html
https://www.ibm.com/developerworks/cn/java/jackson-advanced-application/index.html
http://www.manongjc.com/article/114528.html
https://www.baeldung.com/jackson-object-mapper-tutorial