-2

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?

zyydoosh
  • 387
  • 2
  • 14
  • 3
    What do you think `mapper.readValue(responseStream, custom2[].class)` does? (Specifically the `custom2[]`.) Why do you assign the result of that (wrapped in a list) to a `List`? – Sotirios Delimanolis Dec 27 '21 at 12:52
  • Unrelated: [java naming convention](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html) – jhamon Dec 27 '21 at 12:55
  • I edit it, It should be custom1[] not custom2[], but this is not the problem – zyydoosh Dec 27 '21 at 13:21

2 Answers2

1

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<>() {});
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
0

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.
zyydoosh
  • 387
  • 2
  • 14