Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to map String to Object [duplicate]

Tags:

java

jackson

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.

like image 534
kar Avatar asked Dec 18 '22 17:12

kar


2 Answers

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.

like image 103
Shubham Kadlag Avatar answered Jan 05 '23 12:01

Shubham Kadlag


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.

like image 24
Michał Krzywański Avatar answered Jan 05 '23 11:01

Michał Krzywański