zoukankan      html  css  js  c++  java
  • [转载]Jackson Ignore Properties on Marshalling(Jackson进行JSON序列化时忽略指定的属性)

    Original: https://www.baeldung.com/jackson-ignore-properties-on-serialization

    1. Overview

    This tutorial will show how to ignore certain fields when serializing an object to JSON using Jackson 2.x.

    This is very useful when the Jackson defaults aren't enough and we need to control exactly what gets serialized to JSON – and there are several ways to ignore properties.

    If you want to dig deeper and learn other cool things you can do with the Jackson – head on over to the main Jackson tutorial.

    Further reading:

    Intro to the Jackson ObjectMapper

    The article discusses Jackson's central ObjectMapper class, basic serialization and deserialization as well as configuring the two processes.

    Read more

    Jackson Streaming API

    A quick overview of Jackson's Streaming API for processing JSON, including the examples

    Read more

    Guide to @JsonFormat in Jackson

    A quick and practical guide to the @JsonFormat annotation in Jackson.

    Read more

    2. Ignore Fields at the Class Level

    We can ignore specific fields at the class level, using the @*JsonIgnoreProperties* annotation and specifying the fields by name:

    @JsonIgnoreProperties(value = { "intValue" })
    public class MyDto {
    
        private String stringValue;
        private int intValue;
        private boolean booleanValue;
    
        public MyDto() {
            super();
        }
    
        // standard setters and getters are not shown
    }
    

    We can now test that, after the object is written to JSON, the field is indeed not part of the output:

    @Test
    public void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect()
      throws JsonParseException, IOException {
     
        ObjectMapper mapper = new ObjectMapper();
        MyDto dtoObject = new MyDto();
    
        String dtoAsString = mapper.writeValueAsString(dtoObject);
    
        assertThat(dtoAsString, not(containsString("intValue")));
    }
    

    3. Ignore Field at the Field Level

    We can also ignore a field directly via the @*JsonIgnore* annotation directly on the field:

    public class MyDto {
    
        private String stringValue;
        @JsonIgnore
        private int intValue;
        private boolean booleanValue;
    
        public MyDto() {
            super();
        }
    
        // standard setters and getters are not shown
    }
    

    We can now test that the intValue field is indeed not part of the serialized JSON output:

    @Test
    public void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect() 
      throws JsonParseException, IOException {
     
        ObjectMapper mapper = new ObjectMapper();
        MyDto dtoObject = new MyDto();
    
        String dtoAsString = mapper.writeValueAsString(dtoObject);
    
        assertThat(dtoAsString, not(containsString("intValue")));
    }
    

    4. Ignore All Fields by Type

    Finally, we can ignore all fields of a specified type, using the @*JsonIgnoreType* annotation. If we control the type, then we can annotate the class directly:

    @JsonIgnoreType
    public class SomeType { ... }
    

    More often than not, however, we don't have control of the class itself; in this case, we can make good use of Jackson mixins.

    First, we define a MixIn for the type we'd like to ignore, and annotate that with @JsonIgnoreType instead:

    @JsonIgnoreType
    public class MyMixInForIgnoreType {}
    

    Then we register that mixin to replace (and ignore) all String[] types during marshaling:

    mapper.addMixInAnnotations(String[].class, MyMixInForIgnoreType.class);
    

    At this point, all String arrays will be ignored instead of marshaled to JSON:

    @Test
    public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect()
      throws JsonParseException, IOException {
     
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
        MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
        dtoObject.setBooleanValue(true);
    
        String dtoAsString = mapper.writeValueAsString(dtoObject);
    
        assertThat(dtoAsString, containsString("intValue"));
        assertThat(dtoAsString, containsString("booleanValue"));
        assertThat(dtoAsString, not(containsString("stringValue")));
    }
    

    and here is our DTO:

    public class MyDtoWithSpecialField {
        private String[] stringValue;
        private int intValue;
        private boolean booleanValue;
    }
    

    Note: Since version 2.5 – it seems that we can not use this method to ignore primitive data types, but we can use it for custom data types and arrays.

    5. Ignore Fields Using Filters

    Finally, we can also use filters to ignore specific fields in Jackson. First, we need to define the filter on the Java object:

    @JsonFilter("myFilter")
    public class MyDtoWithFilter { ... }
    

    Then, we define a simple filter that will ignore the intValue field:

    SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
      .serializeAllExcept("intValue");
    FilterProvider filters = new SimpleFilterProvider()
      .addFilter("myFilter", theFilter);
    

    Now we can serialize the object and make sure that the intValue field is not present in the JSON output:

    @Test
    public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() 
      throws JsonParseException, IOException {
     
        ObjectMapper mapper = new ObjectMapper();
        SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
          .serializeAllExcept("intValue");
        FilterProvider filters = new SimpleFilterProvider()
          .addFilter("myFilter", theFilter);
    
        MyDtoWithFilter dtoObject = new MyDtoWithFilter();
        String dtoAsString = mapper.writer(filters).writeValueAsString(dtoObject);
    
        assertThat(dtoAsString, not(containsString("intValue")));
        assertThat(dtoAsString, containsString("booleanValue"));
        assertThat(dtoAsString, containsString("stringValue"));
        System.out.println(dtoAsString);
    }
    

    6. Conclusion

    The article illustrated how to ignore fields on serialization – first by name, then directly, and finally – we ignored the entire java type with MixIns and we use filters for more control of the output.

    The implementation of all these examples and code snippets can be found in my GitHub project.

    本博客(liqipeng)除非已明确说明转载,否则皆为liqipeng原创或者整理,转载请保留此链接:https://www.cnblogs.com/liqipeng/p/15552770.html

    本博客(liqipeng)除非已明确说明转载,否则皆为liqipeng原创或者整理,转载请保留此链接:https://www.cnblogs.com/liqipeng/p/15552770.html
    如果你觉得这篇文章对你有帮助或者使你有所启发,请点击右下角的推荐按钮,谢谢,:)
  • 相关阅读:
    HarmonyOS Java UI之DirectionalLayout布局
    【HarmonyOS HiSpark IPC DIY Camera】hi3518wifi的配置与使用
    《鸿蒙开发板外设控制》直播答疑(初学者必看)
    【鸿蒙应用开发】确切位置布局PositionLayout
    鸿蒙应用开发之怎么更好的远程连接手表模拟器做调试
    [Hi3861]实现S1,S2,User三个物理按键的独立事件下(DTButtonV0.0.3)
    鸿蒙开发板外设控制 之 实现物理按键的“长按事件”(按键通用框架 V0.0.2)
    单一方向布局实现音乐播放UI
    鸿蒙系统应用开发之JS实现一个简单的List
    动态设置cxgrid列的Properties
  • 原文地址:https://www.cnblogs.com/liqipeng/p/15552770.html
Copyright © 2011-2022 走看看