【发布时间】: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的方法是怎么调用的?