【问题标题】:Jackson: deserialize with Builder along with standard setters/getters?Jackson:使用 Builder 和标准 setter/getter 反序列化?
【发布时间】:2019-04-23 19:37:17
【问题描述】:

Jackson 是否可以使用 Builder 模式以及默认的 setter 和 getter 方法反序列化 json?

我的对象是使用仅涵盖必需(最终)字段的 Builder 创建的,但我有一些非最终字段以及需要使用 setter 反序列化的值。

下面是抛出异常以尝试反序列化的示例:

new ObjectMapper().readValue(json, Foo.class);

json - 使用默认 Jackson 序列化器序列化的 json 表示,例如:

objectMapper.writeValueAsString(foo);

@Getter
@Setter
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonDeserialize(builder = Foo.Builder.class)
public class Foo {
    private final String key;
    private final Long user;
    private final String action;
    private final String material;
    private final String currency;

    private Foo(String key, Long user, String action, String material, String currency) {
        this.key = key;
        this.user = user;
        this.action = action;
        this.material = material;
        this.currency = currency;
    }

    public static class Builder {
        private  String key;
        private Long user;
        private String action;
        private String material;
        private String currency;

        @JsonProperty("key")
        public Foo.Builder withKey(String key) {
            this.key = key;
            return this;
        }

        @JsonProperty("user")
        public Foo.Builder withUser(Long user) {
            this.user = user;
            return this;
        }

        @JsonProperty("action")
        public Foo.Builder withAction(String action) {
            this.action = action;
            return this;
        }

        /// other 'with' setters....
    }

    @JsonProperty("state")
    private int state;

    @JsonProperty("stat")
    private String stat;

    @JsonProperty("step")
    private String step;
}

它抛出的异常如下:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: 无法识别的字段“状态”(com.Foo$Builder 类),未标记为 可忽略(5 个已知属性:“key”、“user”、“action”、“material”、 "货币",])

如果不可能,哪种解决方法最便宜?

【问题讨论】:

  • 尝试使用 @JsonIgnoreProperties(ignoreUnknown = true) 注释您的课程。
  • 还是没有结果
  • 构造POJO的方法是怎么调用的?

标签: java json jackson builder


【解决方案1】:

两点可疑:

  • 您愿意在Foo 类中使用构建器。在这种情况下,您应该更正规范 (SessionData.Builder.class 在这种情况下不正确)。
  • 您确实在尝试使用外部构建器。在这种情况下,您应该删除或至少将内部构建器标记为可忽略,这似乎是您获得异常的原因。

在这两种情况下,您都应确保获取Foo 实例的最终方法称为build(),否则您应使用@JsonPOJOBuilder(buildMethodName = "nameOfMethod", withPrefix = "set") 注释构建器。

【讨论】:

  • 我的错,已编辑注释,抱歉。肯定是内部构建器)不,仍然没有进展,可能会使用自定义反序列化器,因为我在 Foo 内部遇到了多个像这样的瓶颈。
猜你喜欢
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多