【问题标题】:Jackson: Serialize only marked fields杰克逊:仅序列化标记的字段
【发布时间】:2014-05-05 06:58:35
【问题描述】:

我正在尝试做一些在 gson 中很容易的事情。由于我切换到 Jackson 作为序列化程序,我不知道如何实现:

我只想序列化已由 Annotation 标记的字段。 GSON 代码为:

class Foo {
    @Expose
    public String sometext="Hello World";
    @Expose
    public int somenumber=30;
    public float noop=1.0;
    ...
 }

这应该导致(JSON)

 {
    Foo: {
        sometext:'Hello World',
        somenumber: 30
    }
 }

(语法错误可能被忽略 - 源代码仅用于演示)

那么,gson 的 @Exposenew GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 对应的 Jackson 是什么?

【问题讨论】:

    标签: java json serialization jackson gson


    【解决方案1】:

    在杰克逊,你做相反的事情。用@JsonIgnore注释你不想要的字段。

    标记注解,表示被注解的方法或字段是 被基于自省的序列化和反序列化忽略 功能。也就是说,它不应该被认为是“getter”、“setter” 或“创造者”。

    【讨论】:

    • 我知道,问题是我的类有更多的字段被忽略,而不是被序列化。例如50 个字段,其中只有一个应该被序列化。所以反过来就是选择的方法。
    • @k_wave 据我所知,没有开箱即用的功能。
    • @k_wave 如果您愿意更改字段/getter/setter 上的访问修饰符,您可以使用可见性。
    【解决方案2】:

    似乎有一种方法可以将ObjectMapper 配置为忽略所有未注释的字段。

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(getSerializationConfig().getDefaultVisibilityChecker()
    .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
    .withFieldVisibility(JsonAutoDetect.Visibility.NONE)
    .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
    .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
    .withSetterVisibility(JsonAutoDetect.Visibility.NONE));
    

    Source

    【讨论】:

    • 此方法自 2.6 起已弃用
    【解决方案3】:

    new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); 对应的是初始化一个 ObjectMapper,如下所示:

    ...
    ObjectMapper objectMapper = new ObjectMapper();        
    objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS,
                MapperFeature.AUTO_DETECT_FIELDS,
                MapperFeature.AUTO_DETECT_GETTERS,
                MapperFeature.AUTO_DETECT_IS_GETTERS);
    ...
    

    @Expose 的对应项是 @JsonProperty。使用上面的示例 bean:

    class Foo {
        @JsonProperty
        public String sometext="Hello World";
        @JsonProperty
        public int somenumber=30;
        public float noop=1.0;
        ...
     }
    

    请参阅this answer 来回答一个非常相似的问题。

    【讨论】:

      【解决方案4】:

      如果您只希望它用于特定类型,您也可以只使用注释:

      @JsonAutoDetect(
          fieldVisibility = Visibility.NONE,
          setterVisibility = Visibility.NONE,
          getterVisibility = Visibility.NONE,
          isGetterVisibility = Visibility.NONE,
          creatorVisibility = Visibility.NONE
      )
      public class Foo  {
          @JsonProperty
          public String sometext="Hello World";
          @JsonProperty
          public int somenumber=30;
          // noop won't get serialized
          public float noop= 1.0f;
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 2013-07-10
      • 2015-05-18
      • 2021-04-02
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多