Aleksander Mielczarek
Aleksander Mielczarek

Reputation: 2825

Jackson - map selected fields from JSON to new class instance

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

Answers (1)

Glorfindel
Glorfindel

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

Related Questions