Reputation: 2825
I want to map incoming JSON to class Foo. But I have problem with barBaz field wchich is null. I think maybe I misunderstood purpose of @JsonCreator. Here is my code:
incoming JSON:
{
"foo": "1",
"bar": 2,
"baz": 3
}
data:
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...
}
Upvotes: 1
Views: 380
Reputation: 22651
It doesn't work because barBaz
is nowhere in the JSON. It would work if you change it like this:
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...
}
Upvotes: 2