【Jackson技术专题】全方位系统化学习和使用指南

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Jackson的基本简介","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" ","attrs":{}},{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" Jackson是当前用的比较广泛的,用来序列化和反序列化 json 的 Java 的开源框架。Jackson 社 区相对比较活跃,更新速度也比较快, 从 Github 中的统计来看,Jackson 是最流行的 json 解析器之一 。 Spring MVC 的默认json解析器便是 Jackson。","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"Jackson 所依赖的 jar 包较少 ,简单易用。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"Jackson 解析大的 json 文件速度比较快;","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"Jackson 运行时占用内存比较低,性能比较好;","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"Jackson 有灵活的 API,可以很容易进行扩展和定制。","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"  Jackson 的 1.x 版本的包名是","attrs":{}},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"org.codehaus.jackson","attrs":{}}],"attrs":{}},{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" ,当升级到 2.x 版本时,包名变为 ","attrs":{}},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"com.fasterxml.jackson","attrs":{}}],"attrs":{}},{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":",本文讨论的内容是基于最新的 Jackson 的 2.9.1 版本。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Jackson的核心模块","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"jackson-core:核心包,提供基于\"流模式\"解析的相关 API,它包括 JsonParser 和 JsonGenerator。 Jackson 内部实现正是通过高性能的流模式 API 的 JsonGenerator 和 JsonParser 来生成和解析 json。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"jackson-annotations:注解包,提供标准注解功能;","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"jackson-databind:数据绑定包, 提供基于\"对象绑定\" 解析的相关 API ( ObjectMapper ) 和\"树模型\" 解析的相关 API (JsonNode);基于\"对象绑定\" 解析的 API 和\"树模型\"解析的 API 依赖基于\"流模式\"解析的 API。","attrs":{}}]}]}],"attrs":{}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Jackson 的基本用法","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"  若想在 Java 代码中使用 Jackson 的核心模块的 jar 包 ,需要在 pom.xml 中添加如下信息。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"清单 1.在 pom.xml 的 Jackson 的配置信息","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":" \n com.fasterxml.jackson.core \n jackson-databind \n 2.9.1 \n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" ","attrs":{}},{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"jackson-databind 依赖 jackson-core 和 jackson-annotations,当添加 jackson-databind 之后, jackson-core 和 jackson-annotations 也随之添加到 Java 项目工程中。在添加相关依赖包之后,就可以使用 Jackson。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"ObjectMapper的使用示例","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" Jackson 最常用的 API 就是基于\"对象绑定\" 的 ObjectMapper。下面是一个 ObjectMapper 的使用的简单示例。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"ObjectMapper mapper = new ObjectMapper(); \nPerson person = new Person(); \nperson.setName(\"Tom\"); \nperson.setAge(40); \nString jsonString = mapper.writerWithDefaultPrettyPrinter() \n .writeValueAsString(person); \nPerson deserializedPerson = mapper.readValue(jsonString, Person.class);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" ","attrs":{}},{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"ObjectMapper 通过 writeValue 系列方法 将 java 对 象序列化 为 json,并 将 json存储成不同的格式,String(writeValueAsString),Byte Array(writeValueAsString),Writer, File,OutStream 和 DataOutput。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" ObjectMapper 通过 readValue 系列方法从不同的数据源像 String , Byte Array, Reader,File,URL, InputStream 将 json 反序列化为 java 对象。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"ObjectMapper的信息配置","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" 在调用 writeValue 或调用 readValue 方法之前,往往需要设置 ObjectMapper 的相关配置信息。这些配置信息应用 java 对象的所有属性上。示例如下:","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":5},"content":[{"type":"text","text":"配置信息使用示例","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"//在反序列化时忽略在 json 中存在但 Java 对象不存在的属性 \nmapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); \n//在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSSZ \nmapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false) \n//在序列化时忽略值为 null 的属性 \nmapper.setSerializationInclusion(Include.NON_NULL); \n//忽略值为默认值的属性 \nmapper.setDefaultPropertyInclusion(Include.NON_DEFAULT);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"更多配置信息可以查看 Jackson 的 DeserializationFeature,SerializationFeature 和Include。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Jackson的注解使用","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" Jackson 根据它的默认方式序列化和反序列化 java 对象,若根据实际需要,灵活的调整它的默认方式,可以使用 Jackson 的注解。常用的注解及用法如下。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"Jackson的常用注解","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonProperty:用于属性,把属性的名称序列化时转换为另外一个名称。示例:@JsonProperty(\"birth_ d ate\") private Date birthDate;","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonFormat\t用于属性或者方法,把属性的格式序列化时转换成指定的格式。示例:@JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm\") public Date getBirthDate()","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonPropertyOrder 用于类, 指定属性在序列化时 json 中的顺序 , 示例:@JsonPropertyOrder({ \"birth_Date\", \"name\" }) public class Person;","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonCreator\t用于构造方法,和 @JsonProperty 配合使用,适用有参数的构造方法。 示例:@JsonCreator public Person(@JsonProperty(\"name\")String name) {…}","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonAnySetter 用于属性或者方法,设置未反序列化的属性名和值作为键值存储到 map 中@JsonAnySetter public void set(String key, Object value) { map.put(key, value); }","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"@JsonAnyGetter 用于方法 ,获取所有未序列化的属性 public Map any() { return map; }","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在了解 Jackson 的基本用法后,下面详细地介绍它的一些高阶应用。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"Jackson 的高阶应用","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"格式处理(含日期格式)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不同类型的日期类型,Jackson的处理方式也不同。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"日期类型: java.util.Calendar,java.util.GregorianCalendar,java.sql.Date,java.util.Date,java.sql.Timestamp,若不指定格式,在json文件中将序列化为long类型的数据。显然这种默认格式,可读性差,转换格式是必要的。Jackson有很多方式转换日期格式。注解方式,请参照\" Jackson 的注解的使用\"的@ JsonFormat 的示例。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"ObjectMapper方式,调用ObjectMapper 的方法setDateFormat,将序列化为指定格式的 string 类型的数据。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"日期类型:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" java.time.LocalDate,还需要添加代码 mapper.registerModule(new JavaTimeModule()),同时添加相应的依赖 jar 包","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":" \n com.fasterxml.jackson.datatype \n jackson-datatype-jsr310 \n 2.9.1 \n","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"对于 Jackson 2.5 以下版本,需要添加代码 objectMapper.registerModule(new JSR310Module ())","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"日期类型:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"org.joda.time.DateTime","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"还需要添加代码 mapper.registerModule(new JodaModule()),同时添加相应的依赖 jar 包","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":" \n com.fasterxml.jackson.datatype\n jackson-datatype-joda \n 2.9.1 \n","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"泛型反序列化","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" Jackson 对泛型反序列化也提供很好的支持。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 对于 List 类型 ,可以调用 constructCollectionType 方法来序列化,也可以构造 TypeReference 来序列化。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"CollectionType javaType = mapper.getTypeFactory() \n .constructCollectionType(List.class, Person.class); \nList personList = mapper.readValue(jsonInString, javaType); \nList personList = mapper.readValue(jsonInString,new TypeReference>(){});","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"对于 map 类型, 与 List 的实现方式相似。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"//第二参数是 map 的 key 的类型,第三参数是 map 的 value 的类型 \nMapType javaType =\n mapper.getTypeFactory().constructMapType(HashMap.class,String.class,\n Person.class); \n Map personMap = mapper.readValue(jsonInString, javaType); \n Map personMap = mapper.readValue(jsonInString,new TypeReference>() {});","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Array 和 Collection 的处理与 List,Map 相似,这里不再详述。","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"属性可视化","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 是 java 对象的所有的属性都被序列化和反序列化,换言之,不是所有属性都可视化,默认的属性可视化的规则如下:","attrs":{}}]},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"若该属性修饰符是 public,该属性可序列化和反序列化。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"若属性的修饰符不是 public,但是它的 getter 方法和 setter 方法是 public,该属性可序列化和反序列化。因为 getter 方法用于序列化, 而 setter 方法用于反序列化。","attrs":{}}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":1,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"若属性只有 public 的 setter 方法,而无 public 的 getter 方 法,该属性只能用于反序列化。","attrs":{}}]}]}],"attrs":{}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"若想更改默认的属性可视化的规则,需要调用 ObjectMapper 的方法 setVisibility。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面的示例使修饰符为 protected 的属性 name 也可以序列化和反序列化。","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); \npublic class Person { \n public int age; \n protected String name; \n} ","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"PropertyAccessor 支持的类型有:","attrs":{}}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}},{"type":"strong","attrs":{}}],"text":"ALL,CREATOR,FIELD,GETTER,IS_GETTER,NONE,SETTER ","attrs":{}}]}],"attrs":{}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"Visibility ","attrs":{}}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong","attrs":{}}],"text":"支持的类型有:ANY,DEFAULT,NON_PRIVATE,NONE,PROTECTED_AND_PUBLIC,PUBLIC_ONLY","attrs":{}}],"attrs":{}}]}],"attrs":{}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"属性过滤(1)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":" 在将 Java 对象序列化为 json 时 ,有些属性需要过滤掉,不显示在 json 中 , Jackson 有多种实现方法。注解方式, 可以用 @JsonIgnore 过滤单个属性或用 @JsonIgnoreProperties 过滤多个属性,示例如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@JsonIgnore \npublic int getAge() \n@JsonIgnoreProperties(value = { \"age\",\"birth_date\" }) \npublic class Person","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"属性过滤(2)","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"addMixIn 方法加注解方式@JsonIgnoreProperties。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"addMixIn 方法签名如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ObjectMapper addMixIn(Class> target, Class> mixinSource);","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 设置 Filter 类或接口 ,SimpleBeanPropertyFilter 方式。这种方式比前两种方式更加灵活,也更复杂一些。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 首先需要设置@JsonFilter 类或接口,其次设置 addMixIn,将@JsonFilter 作用于 java 对象上,最后调用 SimpleBeanPropertyFilter 的 serializeAllExcept 方法或重写 SimpleBeanPropertyFilter 的 serializeAsField 方法来过滤相关属性。示例如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" @JsonFilter(\"myFilter\") \npublic interface MyFilter {} \n//设置 addMixIn \nmapper.addMixIn(Person.class, MyFilter.class); \n//调用 SimpleBeanPropertyFilter 的 serializeAllExcept 方法 \nSimpleBeanPropertyFilter newFilter = \n SimpleBeanPropertyFilter.serializeAllExcept(\"age\"); \n//或重写 SimpleBeanPropertyFilter 的 serializeAsField 方法 \n SimpleBeanPropertyFilter newFilter = new SimpleBeanPropertyFilter() { \n @Override \n public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer) throws Exception { \n if (!writer.getName().equals(\"age\")) { \n writer.serializeAsField(pojo, jgen, provider); \n } \n } \n}; \n//设置 FilterProvider \nFilterProvider filterProvider = new SimpleFilterProvider() \n .addFilter(\"myFilter\", newFilter); \nmapper.setFilterProvider(filterProvider).writeValueAsString(person);","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"自定义序列化和反序列化","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 当 Jackson 默认序列化和反序列化的类不能满足实际需要,可以自定义新的序列化和反序列化的类。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"自定义序列化类。自定义的序列化类需要直接或间接继承 StdSerializer 或 JsonSerializer,同时需要利用 JsonGenerator 生成 json,重写方法 serialize,示例如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class CustomSerializer extends StdSerializer { \n\n @Override \n\n public void serialize(Person person, JsonGenerator jgen, SerializerProvider provider) throws IOException { \n\n jgen.writeStartObject(); \n\n jgen.writeNumberField(\"age\", person.getAge()); \n\n jgen.writeStringField(\"name\", person.getName()); \n\n jgen.writeEndObject(); \n\n } \n\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" JsonGenerator 有多种 write 方法以支持生成复杂的类型的 json,比如 writeArray,writeTree 等 。若想单独创建 JsonGenerator,可以通过 JsonFactory() 的 createGenerator。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 自定义反序列化类。自定义的反序列化类需要直接或间接继承 StdDeserializer 或 StdDeserializer,同时需要利用 JsonParser 读取 json,重写方法 deserialize,示例如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class CustomDeserializer extends StdDeserializer { \n\n @Override \n\n public Person deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { \n\n JsonNode node = jp.getCodec().readTree(jp); \n\n Person person = new Person(); \n\n int age = (Integer) ((IntNode) node.get(\"age\")).numberValue(); \n\n String name = node.get(\"name\").asText(); \n\n person.setAge(age); \n\n person.setName(name); \n\n return person; \n\n } \n\n}","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" JsonParser 提供很多方法来读取 json 信息, 如 isClosed(), nextToken(), getValueAsString()等。若想单独创建 JsonParser,可以通过 JsonFactory() 的 createParser。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 定义好自定义序列化类和自定义反序列化类,若想在程序中调用它们,还需要注册到 ObjectMapper 的 Module,示例如下:","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"SimpleModule module = new SimpleModule(\"myModule\"); \nmodule.addSerializer(new CustomSerializer(Person.class)); \nmodule.addDeserializer(Person.class, new CustomDeserializer()); \nmapper.registerModule(module); ","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 也可通过注解方式加在 java 对象的属性,方法或类上面来调用它们, ","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"@JsonSerialize(using = CustomSerializer.class) \n@JsonDeserialize(using = CustomDeserializer.class) \npublic class Person","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"树模型处理","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" Jackson 也提供了树模型(tree model)来生成和解析 json。若想修改或访问 json 部分属性,树模型是不错的选择。树模型由 JsonNode 节点组成。程序中常常使用 ObjectNode,ObjectNode 继承于 JsonNode,示例如下:","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"ObjectNode 生成和解析 json 示例","attrs":{}}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"ObjectMapper mapper = new ObjectMapper(); \n\n//构建 ObjectNode \n\nObjectNode personNode = mapper.createObjectNode(); \n\n//添加/更改属性 \n\npersonNode.put(\"name\",\"Tom\"); \n\npersonNode.put(\"age\",40); \n\nObjectNode addressNode = mapper.createObjectNode(); \n\naddressNode.put(\"zip\",\"000000\"); \n\naddressNode.put(\"street\",\"Road NanJing\"); \n\n//设置子节点 \n\npersonNode.set(\"address\",addressNode); \n\n//通过 path 查找节点 \n\nJsonNode searchNode = personNode.path(\"street \"); \n\n//删除属性 \n\n((ObjectNode) personNode).remove(\"address\"); \n\n//读取 json \n\nJsonNode rootNode = mapper.readTree(personNode.toString()); \n\n//JsonNode 转换成 java 对象 \n\nPerson person = mapper.treeToValue(personNode, Person.class); \n\n//java 对象转换成 JsonNode \n\nJsonNode node = mapper.valueToTree(person);","attrs":{}}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"总结","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 本文首先通过与其他 Java 的 json 的框架比较,介绍了 Jackson 的优点,并且描述了 Jackson 的 核心模块的组成,以及每个部分的作用。然后, 本文通过示例,讲解 Jackson 的基本用法,介绍了 ObjectMapper 的 write 和 read 方法,ObjectMapper 的配置信息设定,以及 jackson-annotations 包下注释的运用。","attrs":{}}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 最后,本文详细的介绍了 Jackson 的高阶用法,这也是本文的重点。这些高阶用法包括不同类型的日期格式处理(普通日期的类型,jdk 8 的日期类型,joda 的日期类型),List 和 Map 等泛型的反序列化,属性的可视化管理,Jackson 的 三种属性过滤方式,自定义序列化和反序列化的实现以及树模型的使用。通过本文的系统地讲解,相信读者对 Jackson 会有更深刻而全面的掌握。","attrs":{}}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章