Jackson:使用Builder和标准setters/getters进行反序列化



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:无法识别的字段"state"(类com.Foo$Builder(,未标记为可忽略(5个已知属性:"键"、"用户"、"动作"、"材料","货币",](

如果不可能,最便宜的解决方法是什么?

两件可疑的事情:

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

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

最新更新