jackson annotations註解詳解

官方WIKI:https://github.com/FasterXML/jackson-databind/wikihtml

jackson 1.x和2.x版本的註解是放置在不一樣的包下的java

1.x是在jackson core jar包org.codehaus.jackson.annotate下git

2.x是在jackson-databind包com.fasterxml.jackson.annotation下github


jackson的自動檢測機制

jackson容許使用任意的構造方法或工廠方法來構造實例數據庫

使用@JsonAutoDetect(做用在類上)來開啓/禁止自動檢測

fieldVisibility:字段的可見級別json

ANY:任何級別的字段均可以自動識別數組

NONE:全部字段都不能夠自動識別app

NON_PRIVATE:非private修飾的字段能夠自動識別ide

PROTECTED_AND_PUBLIC:被protected和public修飾的字段能夠被自動識別函數

PUBLIC_ONLY:只有被public修飾的字段才能夠被自動識別

DEFAULT:同PUBLIC_ONLY

jackson默認的字段屬性發現規則以下:

全部被public修飾的字段->全部被public修飾的getter->全部被public修飾的setter

舉例:

  
  
  
  
  
  1. public static class TestPOJO{
  2. TestPOJO(){}
  3. TestPOJO(String name){
  4. this.name = name;
  5. }
  6. private String name;
  7. @Override
  8. public String toString() {
  9. return "TestPOJO{" +
  10. "name='" + name + '\'' +
  11. '}';
  12. }
  13. }
這個類咱們只有一個private的name屬性,而且沒有提供對應的get,set方法,若是按照默認的屬性發現規則咱們將沒法序列化和反序列化name字段(若是沒有get,set方法,只有被public修飾的屬性纔會被發現),你能夠經過修改@JsonAutoDetect的fieldVisibility來調整自動發現級別,爲了使name被自動發現,咱們須要將級別調整爲ANY

  
  
  
  @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
同理,除了fieldVisibility能夠設置外,還能夠設置getterVisibility、setterVisibility、isGetterVisibility、creatorVisibility級別,再也不多講


除了上面的方式,你還能夠有一些其餘方式能夠配置methods,fields和creators(構造器和靜態方法)的自動檢測,例如:

你能夠配置MapperFeature來啓動/禁止一些特別類型(getters,setters,fields,creators)的自動檢測

好比下面的MapperFeature配置:

SORT_PROPERTIES_ALPHABETICALLY:按字母順序排序屬性

  
  
  
  
  
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

配置SerializationFeature

一些咱們比較經常使用的SerializationFeature配置:

SerializationFeature.WRAP_ROOT_VALUE:是否環繞根元素,默認false,若是爲true,則默認以類名做爲根元素,你也能夠經過@JsonRootName來自定義根元素名稱

  
  
  
  objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE,true);

舉例:

  
  
  
  
  
  1. @JsonRootName( "myPojo")
  2. public static class TestPOJO{
  3. private String name;
  4. public String getName() {
  5. return name;
  6. }
  7. public void setName(String name) {
  8. this.name = name;
  9. }
  10. }
該類在序列化成json後相似以下:{"myPojo":{"name":"aaaa"}}

SerializationFeature.INDENT_OUTPUT:是否縮放排列輸出,默認false,有些場合爲了便於排版閱讀則須要對輸出作縮放排列

  
  
  
  objectMapper.configure(SerializationFeature.INDENT_OUTPUT,true);

舉例:

若是一個類中有a、b、c、d四個可檢測到的屬性,那麼序列化後的json輸出相似下面:

{
  "a" : "aaa",
  "b" : "bbb",
  "c" : "ccc",
  "d" : "ddd"
}

SerializationFeature.WRITE_DATES_AS_TIMESTAMPS:序列化日期時以timestamps輸出,默認true

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,true);
好比若是一個類中有private Date date;這種日期屬性,序列化後爲:{"date" : 1413800730456},若不爲true,則爲{"date" : "2014-10-20T10:26:06.604+0000"}

SerializationFeature.WRITE_ENUMS_USING_TO_STRING:序列化枚舉是以toString()來輸出,默認false,即默認以name()來輸出

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true);

SerializationFeature.WRITE_ENUMS_USING_INDEX:序列化枚舉是以ordinal()來輸出,默認false

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX,true);

舉例:

  
  
  
  
  
  1. @Test
  2. public void enumTest() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. testPOJO.setMyEnum(TestEnum.ENUM01);
  6. ObjectMapper objectMapper = new ObjectMapper();
  7. objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false);
  8. objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false);
  9. String jsonStr1 = objectMapper.writeValueAsString(testPOJO);
  10. Assert.assertEquals( "{\"myEnum\":\"ENUM01\",\"name\":\"myName\"}",jsonStr1);
  11. ObjectMapper objectMapper2 = new ObjectMapper();
  12. objectMapper2.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
  13. String jsonStr2 = objectMapper2.writeValueAsString(testPOJO);
  14. Assert.assertEquals( "{\"myEnum\":\"enum_01\",\"name\":\"myName\"}",jsonStr2);
  15. ObjectMapper objectMapper3 = new ObjectMapper();
  16. objectMapper3.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);
  17. String jsonStr3 = objectMapper3.writeValueAsString(testPOJO);
  18. Assert.assertEquals( "{\"myEnum\":0,\"name\":\"myName\"}",jsonStr3);
  19. }
  20. public static class TestPOJO{
  21. TestPOJO(){}
  22. private TestEnum myEnum;
  23. private String name;
  24. //getters、setters省略
  25. }
  26. public static enum TestEnum{
  27. ENUM01( "enum_01"),ENUM02( "enum_01"),ENUM03( "enum_01");
  28. private String title;
  29. TestEnum(String title) {
  30. this.title = title;
  31. }
  32. @Override
  33. public String toString() {
  34. return title;
  35. }
  36. }

SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED:序列化單元素數組時不以數組來輸出,默認false

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true);
舉例:

  
  
  
  
  
  1. @Test
  2. public void singleElemArraysUnwrap() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. List<Integer> counts = new ArrayList<>();
  6. counts.add( 1);
  7. testPOJO.setCounts(counts);
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. objectMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
  10. String jsonStr1 = objectMapper.writeValueAsString(testPOJO);
  11. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":[1]}",jsonStr1);
  12. ObjectMapper objectMapper2 = new ObjectMapper();
  13. objectMapper2.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
  14. String jsonStr2 = objectMapper2.writeValueAsString(testPOJO);
  15. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":1}",jsonStr2);
  16. }
  17. public static class TestPOJO{
  18. private String name;
  19. private List<Integer> counts;
  20. //getters、setters省略
  21. }

SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS:序列化Map時對key進行排序操做,默認false

  
  
  
  objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,true);
舉例:

  
  
  
  
  
  1. @Test
  2. public void orderMapBykey() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. Map<String,Integer> counts = new HashMap<>();
  6. counts.put( "a", 1);
  7. counts.put( "d", 4);
  8. counts.put( "c", 3);
  9. counts.put( "b", 2);
  10. counts.put( "e", 5);
  11. testPOJO.setCounts(counts);
  12. ObjectMapper objectMapper = new ObjectMapper();
  13. objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);
  14. String jsonStr1 = objectMapper.writeValueAsString(testPOJO);
  15. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":{\"d\":4,\"e\":5,\"b\":2,\"c\":3,\"a\":1}}",jsonStr1);
  16. ObjectMapper objectMapper2 = new ObjectMapper();
  17. objectMapper2.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
  18. String jsonStr2 = objectMapper2.writeValueAsString(testPOJO);
  19. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}}",jsonStr2);
  20. }
  21. public static class TestPOJO{
  22. private String name;
  23. private Map<String,Integer> counts;
  24. //getters、setters省略
  25. }

SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS:序列化char[]時以json數組輸出,默認false

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS,true);
舉例:

  
  
  
  
  
  1. @Test
  2. public void charArraysAsJsonArrays() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. char[] counts = new char[]{ 'a', 'b', 'c', 'd'};
  6. testPOJO.setCounts(counts);
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. objectMapper.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, false);
  9. String jsonStr1 = objectMapper.writeValueAsString(testPOJO);
  10. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":\"abcd\"}",jsonStr1);
  11. ObjectMapper objectMapper2 = new ObjectMapper();
  12. objectMapper2.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, true);
  13. String jsonStr2 = objectMapper2.writeValueAsString(testPOJO);
  14. Assert.assertEquals( "{\"name\":\"myName\",\"counts\":[\"a\",\"b\",\"c\",\"d\"]}",jsonStr2);
  15. }
  16. public static class TestPOJO{
  17. private String name;
  18. private char[] counts;
  19. //getters、setters省略
  20. }

SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN:序列化BigDecimal時之間輸出原始數字仍是科學計數,默認false,便是否以toPlainString()科學計數方式來輸出

  
  
  
  objectMapper.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS,true);
舉例:

  
  
  
  
  
  1. @Test
  2. public void bigDecimalAsPlain() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. testPOJO.setCount( new BigDecimal( "1e20"));
  6. ObjectMapper objectMapper = new ObjectMapper();
  7. objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, false);
  8. String jsonStr1 = objectMapper.writeValueAsString(testPOJO);
  9. Assert.assertEquals( "{\"name\":\"myName\",\"count\":1E+20}",jsonStr1);
  10. ObjectMapper objectMapper2 = new ObjectMapper();
  11. objectMapper2.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
  12. String jsonStr2 = objectMapper2.writeValueAsString(testPOJO);
  13. Assert.assertEquals( "{\"name\":\"myName\",\"count\":100000000000000000000}",jsonStr2);
  14. }
更多的序列化配置參見 點擊打開連接

配置DeserializationFeature

反序列化的配置這裏再也不多作解釋,參見點擊打開連接

須要注意的是對於第二種經過配置SerializationConfig和DeserializationConfig方式只能啓動/禁止自動檢測,沒法修改咱們所需的可見級別

有時候對每一個實例進行可見級別的註解可能會很是麻煩,這時候咱們須要配置一個全局的可見級別,經過objectMapper.setVisibilityChecker()來實現,默認的VisibilityChecker實現類爲VisibilityChecker.Std,這樣能夠知足實現複雜場景下的基礎配置。

也有一些實用簡單的可見級別配置,好比:

  
  
  
  
  
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) // auto-detect all member fields
  3. .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) // but only public getters
  4. .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) // and none of "is-setters"
  5. ;
你也能夠經過下面方式來禁止全部的自動檢測功能
  
  
  
  
  
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. objectMapper.setVisibilityChecker(objectMapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));

jackson的經常使用註解

一、@JsonAutoDetect

看上面自動檢測,再也不重複

二、@JsonIgnore

做用在字段或方法上,用來徹底忽略被註解的字段和方法對應的屬性,即使這個字段或方法能夠被自動檢測到或者還有其餘的註解

舉例

  
  
  
  
  
  1. @Test
  2. public void jsonIgnoreTest() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setId( 111);
  5. testPOJO.setName( "myName");
  6. testPOJO.setCount( 22);
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  9. Assert.assertEquals( "{\"id\":111}",jsonStr);
  10. String jsonStr2 = "{\"id\":111,\"name\":\"myName\",\"count\":22}";
  11. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2, TestPOJO.class);
  12. Assert.assertEquals( 111,testPOJO2.getId());
  13. Assert.assertNull(testPOJO2.getName());
  14. Assert.assertEquals( 0,testPOJO2.getCount());
  15. }
  16. public static class TestPOJO{
  17. private int id;
  18. @JsonIgnore
  19. private String name;
  20. private int count;
  21. public int getId() {
  22. return id;
  23. }
  24. public void setId(int id) {
  25. this.id = id;
  26. }
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public int getCount() {
  34. return count;
  35. }
  36. @JsonIgnore
  37. public void setCount(int count) {
  38. this.count = count;
  39. }
  40. }
當@JsonIgnore無論註解在getters上仍是setters上都會忽略對應的屬性

三、@JsonProperty

做用在字段或方法上,用來對屬性的序列化/反序列化,能夠用來避免遺漏屬性,同時提供對屬性名稱重命名,好比在不少場景下Java對象的屬性是按照規範的駝峯書寫,可是實際展現的倒是相似C-style或C++/Microsolft style

舉例

  
  
  
  
  
  1. @Test
  2. public void jsonPropertyTest() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.wahaha( 111);
  5. testPOJO.setFirstName( "myName");
  6. ObjectMapper objectMapper = new ObjectMapper();
  7. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  8. Assert.assertEquals( "{\"id\":111,\"first_name\":\"myName\"}",jsonStr);
  9. String jsonStr2 = "{\"id\":111,\"first_name\":\"myName\"}";
  10. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2, TestPOJO.class);
  11. Assert.assertEquals( 111, testPOJO2.wahaha());
  12. Assert.assertEquals( "myName", testPOJO2.getFirstName());
  13. }
  14. public static class TestPOJO{
  15. @JsonProperty //注意這裏必須得有該註解,由於沒有提供對應的getId和setId函數,而是其餘的getter和setter,防止遺漏該屬性
  16. private int id;
  17. @JsonProperty( "first_name")
  18. private String firstName;
  19. public int wahaha() {
  20. return id;
  21. }
  22. public void wahaha(int id) {
  23. this.id = id;
  24. }
  25. public String getFirstName() {
  26. return firstName;
  27. }
  28. public void setFirstName(String firstName) {
  29. this.firstName = firstName;
  30. }
  31. }

四、@JsonIgnoreProperties

做用在類上,用來講明有些屬性在序列化/反序列化時須要忽略掉,能夠將它看作是@JsonIgnore的批量操做,但它的功能比@JsonIgnore要強,好比一個類是代理類,咱們沒法將將@JsonIgnore標記在屬性或方法上,此時即可用@JsonIgnoreProperties標註在類聲明上,它還有一個重要的功能是做用在反序列化時解析字段時過濾一些未知的屬性,不然一般狀況下解析到咱們定義的類不認識的屬性便會拋出異常。

能夠註明是想要忽略的屬性列表如@JsonIgnoreProperties({"name","age","title"}),

也能夠註明過濾掉未知的屬性如@JsonIgnoreProperties(ignoreUnknown=true)

舉例:

  
  
  
  
  
  1. @Test(expected = UnrecognizedPropertyException.class)
  2. public void JsonIgnoreProperties() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setId( 111);
  5. testPOJO.setName( "myName");
  6. testPOJO.setAge( 22);
  7. ObjectMapper objectMapper = new ObjectMapper();
  8. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  9. Assert.assertEquals( "{\"id\":111}",jsonStr); //name和age被忽略掉了
  10. String jsonStr2 = "{\"id\":111,\"name\":\"myName\",\"age\":22,\"title\":\"myTitle\"}";
  11. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2, TestPOJO.class);
  12. Assert.assertEquals( 111, testPOJO2.getId());
  13. Assert.assertNull(testPOJO2.getName());
  14. Assert.assertEquals( 0,testPOJO2.getAge());
  15. String jsonStr3 = "{\"id\":111,\"name\":\"myName\",\"count\":33}"; //這裏有個未知的count屬性,反序列化會報錯
  16. objectMapper.readValue(jsonStr3, TestPOJO.class);
  17. }
  18. @JsonIgnoreProperties({ "name", "age", "title"})
  19. public static class TestPOJO{
  20. private int id;
  21. private String name;
  22. private int age;
  23. //getters、setters省略
  24. }
若是將上面的
  
  
  
  @JsonIgnoreProperties({"name","age","title"})

更換爲

  
  
  
  @JsonIgnoreProperties(ignoreUnknown=true)
那麼測試用例中在反序列化未知的count屬性時便不會拋出異常了

五、@JsonUnwrapped

做用在屬性字段或方法上,用來將子JSON對象的屬性添加到封閉的JSON對象,提及來比較難懂,看個例子就很清楚了,很少解釋

舉例

  
  
  
  
  
  1. @Test
  2. public void jsonUnwrapped() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setId( 111);
  5. TestName testName = new TestName();
  6. testName.setFirstName( "張");
  7. testName.setSecondName( "三");
  8. testPOJO.setName(testName);
  9. ObjectMapper objectMapper = new ObjectMapper();
  10. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  11. //若是沒有@JsonUnwrapped,序列化後將爲{"id":111,"name":{"firstName":"張","secondName":"三"}}
  12. //由於在name屬性上加了@JsonUnwrapped,因此name的子屬性firstName和secondName將不會包含在name中。
  13. Assert.assertEquals( "{\"id\":111,\"firstName\":\"張\",\"secondName\":\"三\"}",jsonStr);
  14. String jsonStr2 = "{\"id\":111,\"firstName\":\"張\",\"secondName\":\"三\"}";
  15. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2,TestPOJO.class);
  16. Assert.assertEquals( 111,testPOJO2.getId());
  17. Assert.assertEquals( "張",testPOJO2.getName().getFirstName());
  18. Assert.assertEquals( "三",testPOJO2.getName().getSecondName());
  19. }
  20. public static class TestPOJO{
  21. private int id;
  22. @JsonUnwrapped
  23. private TestName name;
  24. //getters、setters省略
  25. } public static class TestName{
  26. private String firstName;
  27. private String secondName;
  28. //getters、setters省略
  29. }
在2.0+版本中@JsonUnwrapped添加了prefix和suffix屬性,用來對字段添加先後綴,這在有關屬性分組上比較有用,在上面的測試用例中,若是咱們將TestPOJO的name屬性上的@JsonUnwrapped添加先後綴配置,即
  
  
  
  @JsonUnwrapped(prefix = "name_",suffix = "_test")
那麼TestPOJO序列化後將爲{"id":111,"name_firstName_test":"張","name_secondName_test":"三"},反序列化時也要加上先後綴纔會被解析爲POJO

六、@JsonIdentityInfo

2.0+版本新註解,做用於類或屬性上,被用來在序列化/反序列化時爲該對象或字段添加一個對象識別碼,一般是用來解決循環嵌套的問題,好比數據庫中的多對多關係,經過配置屬性generator來肯定識別碼生成的方式,有簡單的,配置屬性property來肯定識別碼的名稱,識別碼名稱沒有限制。
對象識別碼能夠是虛擬的,即存在在JSON中,但不是POJO的一部分,這種狀況下咱們能夠如此使用註解

  
  
  
  @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property = "@id")

對象識別碼也能夠是真實存在的,即以對象的屬性爲識別碼,一般這種狀況下咱們通常以id屬性爲識別碼,能夠這麼使用註解

  
  
  
  @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id")
舉例

  
  
  
  
  
  1. @Test
  2. public void jsonIdentityInfo() throws Exception {
  3. Parent parent = new Parent();
  4. parent.setName( "jack");
  5. Child child = new Child();
  6. child.setName( "mike");
  7. Child[] children = new Child[]{child};
  8. parent.setChildren(children);
  9. child.setParent(parent);
  10. ObjectMapper objectMapper = new ObjectMapper();
  11. String jsonStr = objectMapper.writeValueAsString(parent);
  12. Assert.assertEquals( "{\"@id\":1,\"name\":\"jack\",\"children\":[{\"name\":\"mike\",\"parent\":1}]}",jsonStr);
  13. }
  14. @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class,property = "@id")
  15. public static class Parent{
  16. private String name;
  17. private Child[] children;
  18. //getters、setters省略
  19. }
  20. public static class Child{
  21. private String name;
  22. private Parent parent;
  23. //getters、setters省略
  24. }

這裏須要提醒一下的是在1.6版本中提供了@JsonManagedReference@JsonBackReference來解決循環嵌套問題,由於屬於過期註解這裏就不解釋了,有興趣的能夠本身看

七、@JsonNaming

jackson 2.1+版本的註解,做用於類或方法,注意這個註解是在jackson-databind包中而不是在jackson-annotations包裏,它可讓你定製屬性命名策略,做用和前面提到的@JsonProperty的重命名屬性名稱相同。好比
你有一個JSON串{"in_reply_to_user_id":"abc123"},須要反序列化爲POJO,POJO通常狀況下則須要如此寫

  
  
  
  
  
  1. public static class TestPOJO{
  2. private String in_reply_to_user_id;
  3. public String getIn_reply_to_user_id() {
  4. return in_reply_to_user_id;
  5. }
  6. public void setIn_reply_to_user_id(String in_reply_to_user_id) {
  7. this.in_reply_to_user_id = in_reply_to_user_id;
  8. }
  9. }
但這顯然不符合JAVA的編碼規範,你能夠用@JsonProperty,好比:

  
  
  
  
  
  1. public static class TestPOJO{
  2. @JsonProperty( "in_reply_to_user_id")
  3. private String inReplyToUserId;
  4. public String getInReplyToUserId() {
  5. return inReplyToUserId;
  6. }
  7. public void setInReplyToUserId(String inReplyToUserId) {
  8. this.inReplyToUserId = inReplyToUserId;
  9. }
  10. }
這樣就符合規範了,但是若是POJO裏有不少屬性,給每一個屬性都要加上@JsonProperty是多麼繁重的工做,這裏就須要用到@JsonNaming了,它不只能制定統一的命名規則,還能任意按本身想要的方式定製

舉例

  
  
  
  
  
  1. @Test
  2. public void jsonNaming() throws Exception{
  3. String jsonStr = "{\"in_reply_to_user_id\":\"abc123\"}";
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "abc123",testPOJO.getInReplyToUserId());
  7. TestPOJO testPOJO2 = new TestPOJO();
  8. testPOJO2.setInReplyToUserId( "abc123");
  9. String jsonStr2 = objectMapper.writeValueAsString(testPOJO2);
  10. Assert.assertEquals(jsonStr,jsonStr2);
  11. }
  12. @JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
  13. public static class TestPOJO{
  14. private String inReplyToUserId;
  15. public String getInReplyToUserId() {
  16. return inReplyToUserId;
  17. }
  18. public void setInReplyToUserId(String inReplyToUserId) {
  19. this.inReplyToUserId = inReplyToUserId;
  20. }
  21. }
@JsonNaming使用了jackson已經實現的PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy,它能夠將大寫轉換爲小寫並添加下劃線。你能夠自定義,必須繼承類PropertyNamingStrategy,建議繼承PropertyNamingStrategyBase,咱們本身實現一個相似LowerCaseWithUnderscoresStrategy的策略,只是將下劃線改成破折號

舉例

  
  
  
  
  
  1. @Test
  2. public void jsonNaming() throws Exception{
  3. String jsonStr = "{\"in-reply-to-user-id\":\"abc123\"}";
  4. ObjectMapper objectMapper = new ObjectMapper();
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "abc123", testPOJO.getInReplyToUserId());
  7. TestPOJO testPOJO2 = new TestPOJO();
  8. testPOJO2.setInReplyToUserId( "abc123");
  9. String jsonStr2 = objectMapper.writeValueAsString(testPOJO2);
  10. Assert.assertEquals(jsonStr, jsonStr2);
  11. }
  12. @JsonNaming(MyPropertyNamingStrategy.class)
  13. public static class TestPOJO{
  14. private String inReplyToUserId;
  15. public String getInReplyToUserId() {
  16. return inReplyToUserId;
  17. }
  18. public void setInReplyToUserId(String inReplyToUserId) {
  19. this.inReplyToUserId = inReplyToUserId;
  20. }
  21. }
  22. public static class MyPropertyNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
  23. @Override
  24. public String translate(String input) {
  25. if (input == null) return input; // garbage in, garbage out
  26. int length = input.length();
  27. StringBuilder result = new StringBuilder(length * 2);
  28. int resultLength = 0;
  29. boolean wasPrevTranslated = false;
  30. for ( int i = 0; i < length; i++)
  31. {
  32. char c = input.charAt(i);
  33. if (i > 0 || c != '-') // skip first starting underscore
  34. {
  35. if (Character.isUpperCase(c))
  36. {
  37. if (!wasPrevTranslated && resultLength > 0 && result.charAt(resultLength - 1) != '-')
  38. {
  39. result.append( '-');
  40. resultLength++;
  41. }
  42. c = Character.toLowerCase(c);
  43. wasPrevTranslated = true;
  44. }
  45. else
  46. {
  47. wasPrevTranslated = false;
  48. }
  49. result.append(c);
  50. resultLength++;
  51. }
  52. }
  53. return resultLength > 0 ? result.toString() : input;
  54. }
  55. }
若是你想讓本身定製的策略對全部解析都實現,除了對每一個具體的實體類對應的位置加上@JsonNaming外你還能夠以下作全局配置

  
  
  
  
  
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. objectMapper.setPropertyNamingStrategy( new MyPropertyNamingStrategy());

多態類型處理

jackson容許配置多態類型處理,當進行反序列話時,JSON數據匹配的對象可能有多個子類型,爲了正確的讀取對象的類型,咱們須要添加一些類型信息。能夠經過下面幾個註解來實現:

@JsonTypeInfo

做用於類/接口,被用來開啓多態類型處理,對基類/接口和子類/實現類都有效

  
  
  
  @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "name")
這個註解有一些屬性,

use:定義使用哪種類型識別碼,它有下面幾個可選值:

一、JsonTypeInfo.Id.CLASS:使用徹底限定類名作識別

二、JsonTypeInfo.Id.MINIMAL_CLASS:若基類和子類在同一包類,使用類名(忽略包名)做爲識別碼

三、JsonTypeInfo.Id.NAME:一個合乎邏輯的指定名稱

四、JsonTypeInfo.Id.CUSTOM:自定義識別碼,由@JsonTypeIdResolver對應,稍後解釋

五、JsonTypeInfo.Id.NONE:不使用識別碼

include(可選):指定識別碼是如何被包含進去的,它有下面幾個可選值:

一、JsonTypeInfo.As.PROPERTY:做爲數據的兄弟屬性

二、JsonTypeInfo.As.EXISTING_PROPERTY:做爲POJO中已經存在的屬性

三、JsonTypeInfo.As.EXTERNAL_PROPERTY:做爲擴展屬性

四、JsonTypeInfo.As.WRAPPER_OBJECT:做爲一個包裝的對象

五、JsonTypeInfo.As.WRAPPER_ARRAY:做爲一個包裝的數組

property(可選):制定識別碼的屬性名稱

此屬性只有當use爲JsonTypeInfo.Id.CLASS(若不指定property則默認爲@class)、JsonTypeInfo.Id.MINIMAL_CLASS(若不指定property則默認爲@c)、JsonTypeInfo.Id.NAME(若不指定property默認爲@type),include爲JsonTypeInfo.As.PROPERTY、JsonTypeInfo.As.EXISTING_PROPERTY、JsonTypeInfo.As.EXTERNAL_PROPERTY時纔有效

defaultImpl(可選):若是類型識別碼不存在或者無效,可使用該屬性來制定反序列化時使用的默認類型

visible(可選,默認爲false):是否可見

屬性定義了類型標識符的值是否會經過JSON流成爲反序列化器的一部分,默認爲fale,也就是說,jackson會從JSON內容中處理和刪除類型標識符再傳遞給JsonDeserializer。

@JsonSubTypes

做用於類/接口,用來列出給定類的子類,只有當子類類型沒法被檢測到時纔會使用它

通常是配合@JsonTypeInfo在基類上使用,好比:

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "typeName")
  2. @JsonSubTypes({ @JsonSubTypes.Type(value=Sub1.class,name = "sub1"), @JsonSubTypes.Type(value=Sub2.class,name = "sub2")})
@JsonSubTypes的值是一個@JsonSubTypes.Type[]數組,裏面枚舉了多態類型(value對應類)和類型的標識符值(name對應@JsonTypeInfo中的property標識名稱的值,此爲可選值,若不制定需由@JsonTypeName在子類上制定)

@JsonTypeName

做用於子類,用來爲多態子類指定類型標識符的值

好比:

  
  
  
  @JsonTypeName(value = "sub1")
value屬性做用同上面@JsonSubTypes裏的name做用

@JsonTypeResolver@JsonTypeIdResoler

做用於類,能夠自定義多態的類型標識符,這個平時不多用到,主要是現有的通常就已經知足絕大多數的需求了,若是你須要比較特別的類型標識符,建議使用這2個註解,本身定製基於TypeResolverBuilder和TypeIdResolver的類便可

咱們看幾個jackson處理多態的例子

  
  
  
  
  
  1. @Test
  2. public void jsonTypeInfo() throws Exception{
  3. Sub1 sub1 = new Sub1();
  4. sub1.setId( 1);
  5. sub1.setName( "sub1Name");
  6. Sub2 sub2 = new Sub2();
  7. sub2.setId( 2);
  8. sub2.setAge( 33);
  9. ObjectMapper objectMapper = new ObjectMapper();
  10. TestPOJO testPOJO = new TestPOJO();
  11. testPOJO.setMyIns( new MyIn[]{sub1, sub2});
  12. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  13. Assert.assertEquals( "{\"myIns\":[{\"id\":1,\"name\":\"sub1Name\"},{\"id\":2,\"age\":33}]}", jsonStr);
  14. System.out.println(jsonStr);
  15. }
  16. public static abstract class MyIn{
  17. private int id;
  18. //getters、setters省略
  19. }
  20. public static class Sub1 extends MyIn{
  21. private String name;
  22. //getters、setters省略
  23. }
  24. public static class Sub2 extends MyIn{
  25. private int age;
  26. //getters、setters省略
  27. }
這是序列化時最簡單的一種多態處理方式,由於沒有使用任何多態處理註解,即默認使用的識別碼類型爲JsonTypeInfo.Id.NONE,而jackson沒有自動搜索功能,因此只能序列化而不能反序列化,上面序列化測試的結果爲{"myIns":[{"id":1,"name":"sub1Name"},{"id":2,"age":33}]},咱們能夠看到JSON串中是沒有對應的多態類型識別碼的。

下面咱們在基類MyIn上加上多態處理相關注解,首先咱們在基類MyIn上添加@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)即

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
  2. public static abstract class MyIn{
  3. private int id;
  4. //getters、setters省略
  5. }
執行上面的序列化測試代碼結果將會是

{"myIns":[{"@class":"cn.yangyong.fodder.util.JacksonUtilsTest$Sub1","id":1,"name":"sub1Name"},{"@class":"cn.yangyong.fodder.util.JacksonUtilsTest$Sub2","id":2,"age":33}]}

咱們能夠看到多了相應的多態類型識別碼,識別碼名稱爲默認的@class(由於沒有指定名稱),識別碼的值爲JsonTypeInfo.Id.CLASS即子類徹底限定名

咱們再添加上property屬性@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,property = "typeName")即

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,property = "typeName")
  2. public static abstract class MyIn{
  3. private int id;
  4. //getters、setters省略
  5. }
再次執行上面的序列化測試代碼結果將會是

{"myIns":[{"typeName":"cn.yangyong.fodder.util.JacksonUtilsTest$Sub1","id":1,"name":"sub1Name"},{"typeName":"cn.yangyong.fodder.util.JacksonUtilsTest$Sub2","id":2,"age":33}]}

此次多態類型識別碼的名稱已經變成了咱們指定的typeName而不是默認的@class了

上面的例子都是默認選擇的include爲JsonTypeInfo.As.PROPERTY,下面咱們更改include方式,看看有什麼變化,將include設置爲JsonTypeInfo.As.WRAPPER_OBJECT即

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,include = JsonTypeInfo.As.WRAPPER_OBJECT,property = "typeName")
  2. public static abstract class MyIn{
  3. private int id;
  4. //getters、setters省略
  5. }
再次執行序列化測試,結果爲

{"myIns":[{"cn.yangyong.fodder.util.JacksonUtilsTest$Sub1":{"id":1,"name":"sub1Name"}},{"cn.yangyong.fodder.util.JacksonUtilsTest$Sub2":{"id":2,"age":33}}]}

咱們看到類型識別碼再也不成爲兄弟屬性包含進去了而是爲父屬性將其餘屬性包含進去,此時咱們指定的property=「typeName」已經無用了

再次修改use屬性指定爲JsonTypeInfo.Id.MINIMAL_CLASS,即@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS,include = JsonTypeInfo.As.PROPERTY,property = "typeName")

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS,include = JsonTypeInfo.As.PROPERTY,property = "typeName")
  2. public static abstract class MyIn{
  3. private int id;
  4. //getters、setters省略
  5. }
測試序列化結果爲

{"myIns":[{"typeName":".JacksonUtilsTest$Sub1","id":1,"name":"sub1Name"},{"typeName":".JacksonUtilsTest$Sub2","id":2,"age":33}]}

發現已經沒有同包的package名稱,識別碼的值更加簡短了

測試反序列化

  
  
  
  
  
  1. @Test
  2. public void jsonTypeInfo() throws Exception{
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr2 = "{\"myIns\":[{\"typeName\":\".JacksonUtilsTest$Sub1\",\"id\":1,\"name\":\"sub1Name\"},{\"typeName\":\".JacksonUtilsTest$Sub2\",\"id\":2,\"age\":33}]}";
  5. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2,TestPOJO.class);
  6. MyIn[] myIns = testPOJO2.getMyIns();
  7. for (MyIn myIn : myIns) {
  8. System.out.println(myIn.getClass().getSimpleName());
  9. }
  10. }
結果將會顯示爲Sub1和Sub2說明是能夠實現多態的反序列化的

可能咱們在反序列化時以爲如此傳遞識別碼很不友好,最好能夠自定義識別碼的值,能夠選擇use = JsonTypeInfo.Id.NAME和@JsonSubTypes配合即

  
  
  
  
  
  1. @JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "typeName")
  2. @JsonSubTypes({ @JsonSubTypes.Type(value=Sub1.class,name= "sub1"), @JsonSubTypes.Type(value=Sub2.class,name= "sub2")})
  3. public static abstract class MyIn{
  4. private int id;
  5. //getters、setters省略
  6. }
執行序列化結果爲

{"myIns":[{"typeName":"sub1","id":1,"name":"sub1Name"},{"typeName":"sub2","id":2,"age":33}]}

使用這個結果反序列化也能夠獲得咱們想要的結果,或者在子類上添加@JsonTypeName(value = "sub1")和@JsonTypeName(value = "sub2")以便取代@JsonSubTypes裏的name

若是想不使用@JsonSubTypes來實現反序列化,咱們能夠在ObjectMapper上註冊子類實現,即

  
  
  
  
  
  1. ObjectMapper objectMapper = new ObjectMapper();
  2. objectMapper.registerSubtypes( new NamedType(Sub1.class, "sub1"));
  3. objectMapper.registerSubtypes( new NamedType(Sub2.class, "sub2"));
更多多態處理的例子還請你們本身研究


用於序列化和反序列化的註解類

一、@JsonSerialize@JsonDeserialize

做用於方法和字段上,經過 using(JsonSerializer)和using(JsonDeserializer)來指定序列化和反序列化的實現,一般咱們在須要自定義序列化和反序列化時會用到,好比下面的例子中的日期轉換

  
  
  
  
  
  1. @Test
  2. public void jsonSerializeAndDeSerialize() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. testPOJO.setBirthday( new Date());
  6. ObjectMapper objectMapper = new ObjectMapper();
  7. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  8. System.out.println(jsonStr);
  9. String jsonStr2 = "{\"name\":\"myName\",\"birthday\":\"2014-11-11 19:01:58\"}";
  10. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2,TestPOJO.class);
  11. System.out.println(testPOJO2.toString());
  12. }
  13. public static class TestPOJO{
  14. private String name;
  15. @JsonSerialize(using = MyDateSerializer.class)
  16. @JsonDeserialize(using = MyDateDeserializer.class)
  17. private Date birthday;
  18. //getters、setters省略
  19. @Override
  20. public String toString() {
  21. return "TestPOJO{" +
  22. "name='" + name + '\'' +
  23. ", birthday=" + birthday +
  24. '}';
  25. }
  26. }
  27. private static class MyDateSerializer extends JsonSerializer<Date>{
  28. @Override
  29. public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
  30. DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  31. String dateStr = dateFormat.format(value);
  32. jgen.writeString(dateStr);
  33. }
  34. }
  35. private static class MyDateDeserializer extends JsonDeserializer<Date>{
  36. @Override
  37. public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
  38. String value = jp.getValueAsString();
  39. DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  40. try {
  41. return dateFormat.parse(value);
  42. } catch (ParseException e) {
  43. e.printStackTrace();
  44. }
  45. return null;
  46. }
  47. }
上面的例子中自定義了日期的序列化和反序列化方式,能夠將Date和指定日期格式字符串之間相互轉換。

也能夠經過使用as(JsonSerializer)和as(JsonDeserializer)來實現多態類型轉換,上面咱們有提到多態類型處理時可使用@JsonTypeInfo實現,還有一種比較簡便的方式就是使用@JsonSerialize和@JsonDeserialize指定as的子類類型,注意這裏必須指定爲子類類型才能夠實現替換運行時的類型
  
  
  
  
  
  1. @Test
  2. public void jsonSerializeAndDeSerialize() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. Sub1 sub1 = new Sub1();
  6. sub1.setId( 1);
  7. sub1.setName( "sub1Name");
  8. Sub2 sub2 = new Sub2();
  9. sub2.setId( 2);
  10. sub2.setAge( 22);
  11. testPOJO.setSub1(sub1);
  12. testPOJO.setSub2(sub2);
  13. ObjectMapper objectMapper = new ObjectMapper();
  14. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  15. System.out.println(jsonStr);
  16. String jsonStr2 = "{\"name\":\"myName\",\"sub1\":{\"id\":1,\"name\":\"sub1Name\"},\"sub2\":{\"id\":2,\"age\":22}}";
  17. TestPOJO testPOJO2 = objectMapper.readValue(jsonStr2,TestPOJO.class);
  18. System.out.println(testPOJO2.toString());
  19. }
  20. public static class TestPOJO{
  21. private String name;
  22. @JsonSerialize(as = Sub1.class)
  23. @JsonDeserialize(as = Sub1.class)
  24. private MyIn sub1;
  25. @JsonSerialize(as = Sub2.class)
  26. @JsonDeserialize(as = Sub2.class)
  27. private MyIn sub2;
  28. //getters、setters省略
  29. @Override
  30. public String toString() {
  31. return "TestPOJO{" +
  32. "name='" + name + '\'' +
  33. ", sub1=" + sub1 +
  34. ", sub2=" + sub2 +
  35. '}';
  36. }
  37. }
  38. public static class MyIn{
  39. private int id;
  40. //getters、setters省略
  41. }
  42. public static class Sub1 extends MyIn{
  43. private String name;
  44. //getters、setters省略
  45. @Override
  46. public String toString() {
  47. return "Sub1{" +
  48. "id=" + getId() +
  49. "name='" + name + '\'' +
  50. '}';
  51. }
  52. }
  53. public static class Sub2 extends MyIn{
  54. private int age;
  55. //getters、setters省略
  56. @Override
  57. public String toString() {
  58. return "Sub1{" +
  59. "id=" + getId() +
  60. "age='" + age +
  61. '}';
  62. }
  63. }
上面例子中經過as來指定了須要替換實際運行時類型的子類,實際上上面例子中序列化時是能夠不使用@JsonSerialize(as = Sub1.class)的,由於jackson能夠自動將POJO轉換爲對應的JSON,而反序列化時因爲沒法自動檢索匹配類型必需要指定@JsonDeserialize(as = Sub1.class)方可實現

最後@JsonSerialize能夠配置include屬性來指定序列化時被註解的屬性被包含的方式,默認老是被包含進來,可是能夠過濾掉空的屬性或有默認值的屬性,舉個簡單的過濾空屬性的例子以下

  
  
  
  
  
  1. @Test
  2. public void jsonSerializeAndDeSerialize() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "");
  5. ObjectMapper objectMapper = new ObjectMapper();
  6. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  7. Assert.assertEquals( "{}",jsonStr);
  8. }
  9. public static class TestPOJO{
  10. @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
  11. private String name;
  12. //getters、setters省略
  13. }

二、@JsonPropertyOrder

做用在類上,被用來指明當序列化時須要對屬性作排序,它有2個屬性

一個是alphabetic:布爾類型,表示是否採用字母拼音順序排序,默認是爲false,即不排序

  
  
  
  
  
  1. @Test
  2. public void jsonPropertyOrder() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setA( "1");
  5. testPOJO.setB( "2");
  6. testPOJO.setC( "3");
  7. testPOJO.setD( "4");
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  10. Assert.assertEquals( "{\"a\":\"1\",\"c\":\"3\",\"d\":\"4\",\"b\":\"2\"}",jsonStr);
  11. }
  12. public static class TestPOJO{
  13. private String a;
  14. private String c;
  15. private String d;
  16. private String b;
  17. //getters、setters省略
  18. }
咱們先看一個默認的排序方式,序列化單元測試結果依次爲{"a":"1","c":"3","d":"4","b":"2"},便是沒有通過排序操做的,在TestPOJO上加上@jsonPropertyOrder(alphabetic = true)再執行測試結果將會爲{"a":"1","b":"2","c":"3","d":"4"}
還有一個屬性是value:數組類型,表示將優先其餘屬性排序的屬性名稱

  
  
  
  
  
  1. @Test
  2. public void jsonPropertyOrder() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setA( "1");
  5. testPOJO.setB( "2");
  6. testPOJO.setC( "3");
  7. testPOJO.setD( "4");
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  10. System.out.println(jsonStr);
  11. Assert.assertEquals( "{\"c\":\"3\",\"b\":\"2\",\"a\":\"1\",\"d\":\"4\"}",jsonStr);
  12. }
  13. @JsonPropertyOrder(alphabetic = true,value = { "c", "b"})
  14. public static class TestPOJO{
  15. private String a;
  16. private String c;
  17. private String d;
  18. private String b;
  19. //getters、setters省略
  20. }
上面例子能夠看到value指定了c和b屬性優先排序,因此序列化後爲{"c":"3","b":"2","a":"1","d":"4"}

還記得本文上面最開始配置MapperFeature時也有屬性排序麼,對,就是

  
  
  
  objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true);
只不過@JsonPropertyOrder顆粒度要更細一點,能夠決定哪些屬性優先排序

三、@JsonView

視圖模板,做用於方法和屬性上,用來指定哪些屬性能夠被包含在JSON視圖中,在前面咱們知道已經有@JsonIgnore和@JsonIgnoreProperties能夠排除過濾掉不須要序列化的屬性,但是若是一個POJO中有上百個屬性,好比訂單類、商品詳情類這種屬性超多,而咱們可能只須要概要簡單信息即序列化時只想輸出其中幾個或10幾個屬性,此時使用@JsonIgnore和@JsonIgnoreProperties就顯得很是繁瑣,而使用@JsonView便會很是方便,只許在你想要輸出的屬性(或對應的getter)上添加@JsonView便可,舉例:

  
  
  
  
  
  1. @Test
  2. public void jsonView() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setA( "1");
  5. testPOJO.setB( "2");
  6. testPOJO.setC( "3");
  7. testPOJO.setD( "4");
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
  10. String jsonStr = objectMapper.writerWithView(FilterView.OutputA.class).writeValueAsString(testPOJO);
  11. Assert.assertEquals( "{\"a\":\"1\",\"c\":\"3\"}",jsonStr);
  12. String jsonStr2 = objectMapper.writerWithView(FilterView.OutputB.class).writeValueAsString(testPOJO);
  13. Assert.assertEquals( "{\"d\":\"4\",\"b\":\"2\"}",jsonStr2);
  14. }
  15. public static class TestPOJO{
  16. @JsonView(FilterView.OutputA.class)
  17. private String a;
  18. @JsonView(FilterView.OutputA.class)
  19. private String c;
  20. @JsonView(FilterView.OutputB.class)
  21. private String d;
  22. @JsonView(FilterView.OutputB.class)
  23. private String b;
  24. //getters、setters忽略
  25. }
  26. private static class FilterView {
  27. static class OutputA {}
  28. static class OutputB {}
  29. }
上面的測試用例中,咱們在序列化以前先設置了objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false),看javadoc說這是一個雙向開關,開啓將輸出沒有JsonView註解的屬性,false關閉將輸出有JsonView註解的屬性,惋惜我在測試中開啓開關後有JsonView註解的屬性任然輸出了,你們能夠研究下。序列化時使用了objectMapper.writerWithView(FilterView.OutputA.class).writeValueAsString(testPOJO),即便用哪一個視圖來輸出。在上面的例子中又2種視圖,咱們在序列化的時候能夠選擇想要的視圖來輸出,這在一些地方比較好用,好比安卓、蘋果、桌面等不一樣的客戶端可能會輸出不一樣的屬性。在1.6版本中這個@JsonView註解同時也會強制性自動發現,也就是說無論屬性的可見性以及是否設置了自動發現這些屬性都將會自動被發現,在上例中TestPOJO中的getters、setters能夠不須要也能輸出咱們想要的結果。

四、@JsonFilter

Json屬性過濾器,做用於類,做用同上面的@JsonView,都是過濾掉不想要的屬性,輸出本身想要的屬性。和@FilterView不一樣的是@JsonFilter能夠動態的過濾屬性,好比我不想輸出以system開頭的全部屬性等待,應該說@JsonFilter更高級一點,舉個簡單的例子

  
  
  
  
  
  1. @Test
  2. public void jsonFilter() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setA( "1");
  5. testPOJO.setB( "2");
  6. testPOJO.setC( "3");
  7. testPOJO.setD( "4");
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. FilterProvider filters = new SimpleFilterProvider().addFilter( "myFilter",SimpleBeanPropertyFilter.filterOutAllExcept( "a"));
  10. objectMapper.setFilters(filters);
  11. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  12. Assert.assertEquals( "{\"a\":\"1\"}",jsonStr);
  13. }
  14. @JsonFilter( "myFilter")
  15. public static class TestPOJO{
  16. private String a;
  17. private String c;
  18. private String d;
  19. private String b;
  20. //getters、setters省略
  21. }
上面例子中在咱們想要序列化的POJO上加上了@JsonFilter,表示該類將使用名爲myFilter的過濾器。在測試中定義了一個名爲myFilter的SimpleFilterProvider,這個過濾器將會過濾掉全部除a屬性之外的屬性。這只是最簡單的輸出指定元素的例子,你能夠本身實現FilterProvider來知足你的過濾需求。

有時候咱們可能須要根據現有的POJO來過濾屬性,而這種狀況下一般不會讓你修改已有的代碼在POJO上加註解,這種狀況下咱們就能夠結合@JsonFilter和MixInAnnotations來實現過濾屬性,以下例所示,再也不多作解釋

  
  
  
  
  
  1. @Test
  2. public void jsonFilter() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setA( "1");
  5. testPOJO.setB( "2");
  6. testPOJO.setC( "3");
  7. testPOJO.setD( "4");
  8. ObjectMapper objectMapper = new ObjectMapper();
  9. FilterProvider filters = new SimpleFilterProvider().addFilter( "myFilter",SimpleBeanPropertyFilter.filterOutAllExcept( "a"));
  10. objectMapper.setFilters(filters);
  11. objectMapper.addMixInAnnotations(TestPOJO.class,MyFilterMixIn.class);
  12. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  13. Assert.assertEquals( "{\"a\":\"1\"}",jsonStr);
  14. }
  15. public static class TestPOJO{
  16. private String a;
  17. private String c;
  18. private String d;
  19. private String b;
  20. //getters、setters省略
  21. }
  22. @JsonFilter( "myFilter")
  23. private static interface MyFilterMixIn{
  24. }

五、@JsonIgnoreType

做用於類,表示被註解該類型的屬性將不會被序列化和反序列化,也跟上面幾個同樣屬於過濾屬性功能的註解,舉例:

  
  
  
  
  
  1. @Test
  2. public void jsonFilter() throws Exception {
  3. TestPOJO testPOJO = new TestPOJO();
  4. testPOJO.setName( "myName");
  5. Sub1 sub1 = new Sub1();
  6. sub1.setId( 1);
  7. sub1.setName( "sub1");
  8. Sub2 sub2 = new Sub2();
  9. sub2.setId( 2);
  10. sub2.setAge( 22);
  11. testPOJO.setMyIn(sub1);
  12. testPOJO.setSub1(sub1);
  13. testPOJO.setSub2(sub2);
  14. ObjectMapper objectMapper = new ObjectMapper();
  15. String jsonStr = objectMapper.writeValueAsString(testPOJO);
  16. System.out.println(jsonStr);
  17. }
  18. public static class TestPOJO{
  19. private Sub1 sub1;
  20. private Sub2 sub2;
  21. private MyIn myIn;
  22. private String name;
  23. //getters、setters省略
  24. }
  25. public static class MyIn{
  26. private int id;
  27. //getters、setters省略
  28. }
  29. @JsonIgnoreType
  30. public static class Sub1 extends MyIn{
  31. private String name;
  32. //getters、setters省略
  33. }
  34. @JsonIgnoreType
  35. public static class Sub2 extends MyIn{
  36. private int age;
  37. //getters、setters省略
  38. }
上面例子中咱們在類Sub1和Sub2上都加上了@JsonIgnoreType,那麼須要序列化和反序列時POJO中全部Sub1和Sub2類型的屬性都將會被忽略,上面測試結果爲{"myIn":{"id":1,"name":"sub1"},"name":"myName"},只輸出了name和myIn屬性。須要注意的是@JsonIgnoreType是能夠繼承的,即若是在基類上添加了該註解,那麼子類也至關於加了該註解。在上例中,若是隻在基類MyIn上添加@JsonIgnoreType那麼序列化TestPOJO時將會過濾掉MyIn、Sub一、Sub2。輸出結果爲{"name":"myName"}

六、@JsonAnySetter

做用於方法,在反序列化時用來處理遇到未知的屬性的時候調用,在本文前面咱們知道能夠經過註解@JsonIgnoreProperties(ignoreUnknown=true)來過濾未知的屬性,可是若是須要這些未知的屬性該如何是好?那麼@JsonAnySetter就能夠派上用場了,它一般會和map屬性配合使用用來保存未知的屬性,舉例:

  
  
  
  
  
  1. @Test
  2. public void jsonAnySetter() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"name\":\"myName\",\"code\":\"12345\",\"age\":12}";
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "myName",testPOJO.getName());
  7. Assert.assertEquals( "12345",testPOJO.getOther().get( "code"));
  8. Assert.assertEquals( 12,testPOJO.getOther().get( "age"));
  9. }
  10. public static class TestPOJO{
  11. private String name;
  12. private Map other = new HashMap();
  13. @JsonAnySetter
  14. public void set(String name,Object value) {
  15. other.put(name,value);
  16. }
  17. //getters、setters省略
  18. }
測試用例中咱們在set方法上標註了@JsonAnySetter,每當遇到未知的屬性時都會調用該方法

七、@JsonCreator

做用於方法,一般用來標註構造方法或靜態工廠方法上,使用該方法來構建實例,默認的是使用無參的構造方法,一般是和@JsonProperty或@JacksonInject配合使用,舉例

  
  
  
  
  
  1. @Test
  2. public void jsonCreator() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "myName",testPOJO.getName());
  7. Assert.assertEquals( 12, testPOJO.getAge());
  8. }
  9. public static class TestPOJO{
  10. private String name;
  11. private int age;
  12. @JsonCreator
  13. public TestPOJO(@JsonProperty("full_name") String name,@JsonProperty("age") int age){
  14. this.name = name;
  15. this.age = age;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. }
上面示例中是在構造方法上標註了@JsonCreator,一樣你也能夠標註在靜態工廠方法上,好比:

  
  
  
  
  
  1. @Test
  2. public void jsonCreator() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"name\":\"myName\",\"birthday\":1416299461556}";
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "myName",testPOJO.getName());
  7. System.out.println(testPOJO.getBirthday());
  8. }
  9. public static class TestPOJO{
  10. private String name;
  11. private Date birthday;
  12. private TestPOJO(String name,Date birthday){
  13. this.name = name;
  14. this.birthday = birthday;
  15. }
  16. @JsonCreator
  17. public static TestPOJO getInstance(@JsonProperty("name") String name,@JsonProperty("birthday") long timestamp){
  18. Date date = new Date(timestamp);
  19. return new TestPOJO(name,date);
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public Date getBirthday() {
  25. return birthday;
  26. }
  27. }
這個實例中,TestPOJO的構造方法是私有的,外面沒法new出來該對象,只能經過工廠方法getInstance來構造實例,此時@JsonCreator就標註在工廠方法上。

除了這2種方式外,還有一種構造方式成爲受權式構造器,也是咱們日常比較經常使用到的,這個構造器只有一個參數,且不能使用@JsonProperty。舉例:

  
  
  
  
  
  1. @Test
  2. public void jsonCreator() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "myName",testPOJO.getName());
  7. Assert.assertEquals( 12,testPOJO.getAge());
  8. }
  9. public static class TestPOJO{
  10. private String name;
  11. private int age;
  12. @JsonCreator
  13. public TestPOJO(Map map){
  14. this.name = (String)map.get( "full_name");
  15. this.age = (Integer)map.get( "age");
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. }

八、@JacksonInject

做用於屬性、方法、構造參數上,被用來反序列化時標記已經被注入的屬性,舉例:

  
  
  
  
  
  1. @Test
  2. public void jacksonInject() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"age\":12}";
  5. InjectableValues inject = new InjectableValues.Std().addValue( "name", "myName");
  6. TestPOJO testPOJO = objectMapper.reader(TestPOJO.class).with(inject).readValue(jsonStr);
  7. Assert.assertEquals( "myName", testPOJO.getName());
  8. Assert.assertEquals( 12,testPOJO.getAge());
  9. }
  10. public static class TestPOJO{
  11. @JacksonInject( "name")
  12. private String name;
  13. private int age;
  14. //getters、setters省略
  15. }
上面例子中咱們在反序列化前經過InjectableValues來進行注入咱們想要的屬性

九、@JsonPOJOBuilder

做用於類,用來標註如何定製構建對象,使用的是builder模式來構建,好比Value v = new ValueBuilder().withX(3).withY(4).build();這種就是builder模式來構建對象,一般會喝@JsonDeserialize.builder來配合使用,咱們舉個例子:

  
  
  
  
  
  1. @Test
  2. public void jacksonInject() throws Exception {
  3. ObjectMapper objectMapper = new ObjectMapper();
  4. String jsonStr = "{\"name\":\"myName\",\"age\":12}";
  5. TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
  6. Assert.assertEquals( "myName", testPOJO.getName());
  7. Assert.assertEquals( 12,testPOJO.getAge());
  8. }
  9. @JsonDeserialize(builder=TestPOJOBuilder.class)
  10. public static class TestPOJO{
  11. private String name;
  12. private int age;
  13. public TestPOJO(String name, int age) {
  14. this.name = name;
  15. this.age = age;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. }
  24. @JsonPOJOBuilder(buildMethodName = "create",withPrefix = "with")
  25. public static class TestPOJOBuilder{
  26. private String name;
  27. private int age;
  28. public TestPOJOBuilder withName(String name) {
  29. this.name = name;
  30. return this;
  31. }
  32. public TestPOJOBuilder withAge(int age) {
  33. this.age = age;
  34. return this;
  35. }
  36. public TestPOJO create() {
  37. return new TestPOJO(name,age);
  38. }
  39. }
在TestPOJOBuilder上有@JsonPOJOBuilder註解,表示全部的參數傳遞方法都是以with開頭,最終構建好的對象是經過create方法來得到,而在TestPOJO上使用了@JsonDeserializer,告訴咱們在反序列化的時候咱們使用的是TestPOJOBuilder來構建此對象的


還有一些過時不推薦使用的註解,咱們一筆帶過,主要知道他們是跟哪些其餘註解功能同樣便可

@JsonGetter

做用於方法,1.0版本開始的註解,已通過期,不推薦使用,改用@JsonProperty
@JsonUseSerializer

做用於類和方法,1.5版本開始被移除了,改用@JsonSerialize

@JsonSetter
做用於方法,1.0版本開始的註解,已過時,不推薦使用,改用@JsonProperty

@JsonClass

做用於方法和類,1.9版本開始被移除了,改成@JsonDeserialize.as

@JsonContentClass

做用於方法,1.9版本開始被移除了,改成@JsonDeserialize.contentAs

@JsonKeyClass

做用於方法和類,1.9版本開始被移除了,改成@JsonDeserialize.keyAs

@JsonUseDeserializer

做用於方法和類,1.5版本開始被移除了,改成@JsonDeserialize

原文地址:https://blog.csdn.net/sdyy321/article/details/40298081

相關文章
相關標籤/搜索