【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":{}}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章