【问题标题】:JPA / Jackson - Exclude fields when deserialize and include them when serializeJPA / Jackson - 反序列化时排除字段并在序列化时包含它们
【发布时间】:2017-04-27 21:35:27
【问题描述】:

我有一个带有几个字段的 JPA 实体(真实的更复杂)。我通过 REST(POST 在 Spring 控制器中的操作)接收 一些数据,并立即将其存储在 JPA 实体中;我想看看是否有可能在发送请求时排除某些字段,Jackson 将其反序列化并构造对象。但同时我希望在我发回(对象被序列化)响应时包含这些字段。

@Table("key_card")
public final class KeyCard {
  private String username; // Don't want this to be sent as input,
                           // but want to be able to send it back
                           // in the response
  @NotBlank
  private final char[] password;
}

如果有办法解决这个问题,我只是尽量不要对它进行两次建模(针对请求和响应)。

【问题讨论】:

    标签: java serialization spring-boot jackson


    【解决方案1】:

    您可以使用 JSON 视图:http://wiki.fasterxml.com/JacksonJsonView

    Class Views {
    
       static class AlwaysInclude { }
       static class OnlyOnSerialize extends AlwaysInclude { }
    
    }
    

    然后在你看来:

    @Table("key_card")
    public final class KeyCard {
    
      @JsonView(Views.OnlyOnSerialize.class)
      private String username;
    
      @JsonView(Views.AlwaysInclude.class)
      @NotBlank
      private final char[] password;
    }
    

    【讨论】:

      【解决方案2】:

      要仅从 Json 反序列化中排除 Java 对象属性并在序列化期间包含其值,您可以使用 @JsonIgnore@JsonProperty 注释的适当组合。

      您尤其应该:

      • 使用@JsonIgnore 注释属性本身
      • 用@JsonIgnore 注释它的set 方法
      • 用@JsonProperty 注释它的get 方法

      在这里您可以找到深入的解释和示例:Jackson: using @JsonIgnore and @JsonProperty annotations to exclude a property only from JSON deserialization

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-14
        • 2014-10-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多