我想将传入的JSON映射到Foo类。但是我对barBaz字段wchich有问题。我想也许我误解了@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...
}
最佳答案
它不起作用,因为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...
}