4

I have a JSON value as follows in String format.

{
    "Sample": {
        "name": "some name",
        "key": "some key"
    },
    "Offering": {
        "offer": "some offer",
        "amount": 100
    }
}

Now if I try to map this as follows, it works and maps fine.

//mapper is ObjectMapper;
//data is the above json in String format
Map vo = mapper.readValue(data, Map.class);

But I want to map it to a custom Data class as follows.

Data vo = mapper.readValue(data, Data.class);

When I do this, the result of vo is null.

Refer to following on how the Data class is structured.

@Getter
@Setter
public class Data {
    private Sample sample;
    private Offering offering;
}

@Getter
@Setter
public class Offering {
    public String offer;
    public int amount;
}

@Getter
@Setter
public class Sample {
    private String name;
    private String key;
}

Please advice what I am doing wrong. Thanks.

kar
  • 4,791
  • 12
  • 49
  • 74
  • 1
    Does Jackson actually understand those `@Setter` and `@Getter` annotations? Whenever I've done this I just created the appropriate methods. – markspace Apr 21 '19 at 15:04
  • 1
    I really doubt that vo is null. Its sample and its offering are probably null, though, since since Jackson would expect two properties named `sample` and `offering`, and the JSON contains `Sample` and `Offering` – JB Nizet Apr 21 '19 at 15:04
  • 1
    I see in json its "Sample", but in class its 'sample' – Shubham Kadlag Apr 21 '19 at 15:04
  • 1
    @markspace - that's Lombok. It's a way to generate getters and setters without having to write the getters and setters. – Makoto Apr 21 '19 at 15:19

3 Answers3

5

There seems to be issue with Word Case here. Its "Sample" in your json. But its "sample" in java file. Similarly for Offering.

You can of-course use @JsonProperty if you want to map without changing the case.

Shubham Kadlag
  • 2,248
  • 1
  • 13
  • 32
3

There are two options :

  1. if you can change your json - you have to change Sample to sample and Offering to offering

  2. Change your Data class to :

@Getter
@Setter
public class Data {
    @JsonProperty("Sample")
    private Sample sample;

    @JsonProperty("Offering")
    private Offering offering;
}

In the second option you have to tell Jackson what properties of your input json you want to map to which properties of your class, because by default it will try to map to lowercase properties names.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
3

It may be due to different mapping names of fields in json string and Demo model. "Sample" in json string but "sample" in model class.

You can use @JsonProperty

@JsonProperty("Sample")
private Sample sample;
@JsonProperty("Offering")
private Offering offering;
Vikas
  • 6,868
  • 4
  • 27
  • 41