【问题标题】:Spring Jackson excluding specific properties during serializationSpring Jackson 在序列化期间排除特定属性
【发布时间】:2017-07-10 13:41:29
【问题描述】:

我有一个让控制器返回 Java 对象的 Spring Web 服务。我已将我的服务设置为使用@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE),以便响应在 Json 中。据我了解,Spring 使用 Jackson 将 Java 对象序列化为 Json。我有一个要为其创建自定义 json 序列化程序的类。我想使用自定义序列化程序的唯一原因是避免将 Object 的特定属性序列化为 API 响应的一部分。

例如:

我的控制器方法返回Foo。 Spring 将序列化所有属性作为 API 响应的一部分。但是,我想排除rawBar

public final class Foo{
  Bar propBar;
  Bar intermediateBar;
  Bar rawBar;
  FooBar status;
}

我见过使用StdSerializer<T> 创建自定义序列化程序的示例。但是,这样做意味着我必须编写自定义代码来序列化其他属性。有没有办法排除特定属性?此外,Foo 是第三方库的一部分,因此无法更改该类。是否可以为Foo 创建我自己的序列化程序,然后使用默认序列化程序来序列化除rawBar 之外的所有属性?

【问题讨论】:

    标签: spring serialization jackson


    【解决方案1】:

    其中一个解决方案是创建您自己的类 FooWrapper,其中包含您想要从 foo 获得的属性,将它们复制到 fooWrapper 并从您的控制器返回 fooWrapper。

    public class FooWrapper {
      Bar propBar;
      Bar intermediateBar;      
      FooBar status;
    }
    
    FooWrapper convertFooToFooWrapper(Foo foo) {
      FooWrapper fooWrapper = new FooWrapper ();
      BeanUtils.copyProperties(fooWrapper, foo);
      return fooWrapper ;
    }
    

    【讨论】:

    • Foo 是第三方库的一部分,因此无法更改该类
    • 尝试在需要排除的属性之上使用@JsonIgnore 注释。它在杰克逊图书馆。
    【解决方案2】:

    正如@user12190 所说,最简单的做法是:

    public class Foo {
    
        Bar intermediateBar;
        Bar rawBar;
        FooBar status;
        Bar propBar;
    
        public Bar getPropBar() {
            return propBar;
        }
    
        public void setPropBar(Bar propBar) {
            this.propBar = propBar;
        }
    
        public Bar getIntermediateBar() {
            return intermediateBar;
        }
    
        public void setIntermediateBar(Bar intermediateBar) {
            this.intermediateBar = intermediateBar;
        }
    
        @JsonIgnore
        public Bar getRawBar() {
            return rawBar;
        }
    
        public void setRawBar(Bar rawBar) {
            this.rawBar = rawBar;
        }
    
        public FooBar getStatus() {
            return status;
        }
    
        public void setStatus(FooBar status) {
            this.status = status;
        }
    }
    

    你需要在你的 pom 中包含:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.6</version>
    </dependency>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2011-12-02
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多