我想将传入的JSON映射到类Foo。但我有barBaz字段wchich为null的问题。我想也许我误解了@JsonCreator的目的。这是我的代码:
传入JSON:
{
"foo": "1",
"bar": 2,
"baz": 3
}
数据:
public class Foo {
private String foo;
private BarBaz barBaz;
//getters and setters...
}
public class BarBaz {
private int bar;
private int baz;
public BarBaz() {
}
@JsonCreator
public BarBaz(@JsonProperty("bar") int bar, @JsonProperty("baz") int baz) {
this.bar = bar;
this.baz = baz;
}
//getters and setters...
}
答案 0 :(得分:2)
它不起作用,因为barBaz
在JSON中无处可去。如果你这样改变它会起作用:
public class Foo {
private String foo;
private BarBaz barBaz;
@JsonCreator
public Foo(@JsonProperty("bar") int bar, @JsonProperty("baz") int baz) {
this.barBaz = new BarBaz();
this.barBaz.setBar(bar);
this.barBaz.setBaz(baz);
}
//getters and setters...
}
public class BarBaz {
private int bar;
private int baz;
public BarBaz() {
}
//getters and setters...
}