3

So my question is kind of a spin-off of this answer. I have a JSON response of

{ 
  "Key1": {...},
  "Key2": {...} 
}

and I would like to map it into an object. Since I can't make a wrapper object for what could be 100+ keys, I'd put it all in a Map.

This answer would be great, but I'm not using GSON and am having a hard time doing the same thing with Spring's RestTemplate. When I'd like to parse it to a map with an object as such:

Map<String, RequestObject> map = restTemplate.getForObject("https://example.com/request.json", Map.class);

My RequestObject becomes a LinkedHashMap instead. So map becomes a Map<String, LinkedHashMap>. Which in turn also seems to be holding more LinkedHashMaps. Will I be needing something more complicated like writing my own Jackson Deserializer?

edit:

Unlike in this question (possible duplicate), I do not wish to obtain a generic wrapper. The object will always be the same, but the key varies every time. If it were something as the following:

{
   "Sample":{
      "Key":"2",
      "Object":{
         "Id":"0"
      }
   }
}

I could map it to:

class Sample{
    String key;
    CustomObject object;
}

class CustomObject{
    String id;
}

But since it's of the following form:

{
   "Key1":{
      "Id":"0",
      "Value":"X"
   },
   "Key2":{
      "Id":"1",
      "Value":"Y"
   },
   "Key3":{
      "Id":"2",
      "Value":"Z"
   }
}

I'm not so sure how to map it into a useful representation of the objects represented by each key. (Id & Value here). I can't imagine needing to create a class for every key, so transforming it to a map seems a decent idea. This is not what this question describes.

Community
  • 1
  • 1
Jaims
  • 1,515
  • 2
  • 17
  • 30
  • Possible duplicate of http://stackoverflow.com/questions/8108887/generics-with-spring-resttemplate?rq=1 – Ali Dehghani Mar 31 '16 at 20:02
  • 1
    Possible duplicate of [RestTemplate map JSON key-value pair object with with dynamic keys](https://stackoverflow.com/questions/53494143/resttemplate-map-json-key-value-pair-object-with-with-dynamic-keys) – Jaap Nov 28 '19 at 12:49

0 Answers0