Home > Blockchain >  How to map this json to a custom class in java
How to map this json to a custom class in java

Time:12-28

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?

CodePudding user response:

The error shows that there's no id field causing deserialization failure.

However, the input JSON represents a list/array of maps Map<String, Pojo>, where Pojo should be defined as:

@Data
class Pojo {
    String vr;
    String[] value;
}

Then the JSON should be deserialized using TypeReference:

String json = ...; // long json string
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Pojo>> data = mapper.readValue(json, new TypeReference<>() {});

CodePudding user response:

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.
  • Related