Search code examples
javajsonserializationjacksonobjectmapper

How to map this json to a custom class in java


Let's assume I have the following json

[
    {
        "00080005":{
            "vr":"CS",
            "Value":[
                "ISO_IR 100"
            ]
        },
        "00080054":{
            "vr":"AE",
            "Value":[
                "DCM4CHEE"
            ]
        }
    }
]

How to create a custom class to map this in java? I tried this class shape

public class custom1 {
    private Map<String, cusomt2> id;
}

and cusomt2 shape is

public class cusomt2 {
    private Object vr;
    private Object[] Value;
}

and used Jackson mapper to map

ObjectMapper mapper = new ObjectMapper();
List<custom1> test = Arrays.asList(mapper.readValue(responseStream, custom1[].class));

It's as expected, gives me an error :

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "00080005"

I want "0008005" as the field value not the field key, these values are dynamically changes according to the API, so how to map this json, is there any direct way other the last option op custom deserialize?


Solution

  • I know what is the problem, actually there was 2 problems, @Alex Rudenko solved one, the other problem is that API returns Value as a capital letter, not value, actually I specify it as Value correctly in class, but the problem is that it's a private property, and it's getter named getValue, this confuses jackson when mapping, it considers getValue as a getter of value field not Value

    • First solution(Recommended) was to set @JsonProperty("Value") annotation on the Value property in class.

    So the class now looks like this

    public class custom1 {
    
        private String vr;
        @JsonProperty("Value")
        private String[] Value;
    
        //getter & setters
    }
    
    • second solution is to make Value as public, to avoid using it's getter.