Nested Json on a map using Jackson

I am trying to dynamically parse JSON on a map. The following works well with plain JSON

String easyString = "{\"name\":\"mkyong\", \"age\":\"29\"}"; Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(easyString, new TypeReference<HashMap<String,String>>(){}); System.out.println(map); 

But it fails when I try to use more complex JSON with embedded information. I am trying to analyze sample data from json.org

 { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": [ "GML", "XML" ] }, "GlossSee": "markup" } } } } } 

I get the following error

An exception in the stream "main" com.fasterxml.jackson.databind.JsonMappingException: it is not possible to deserialize an instance of java.lang.String from the START_OBJECT token

Is there a way to parse complex JSON data into a map?

+6
source share
2 answers

I think that the error arises because in a minute Jackson encounters the symbol {, he considers the remaining content as a new object, not a string. Try Object as the map value instead of String.

 public static void main(String[] args) throws IOException { Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(x, new TypeReference<HashMap>(){}); System.out.println(map); } 

Output

 {glossary={title=example glossary, GlossDiv={title=S, GlossList={GlossEntry={ID=SGML, SortAs=SGML, GlossTerm=Standard Generalized Markup Language, Acronym=SGML, Abbrev=ISO 8879:1986, GlossDef={para=A meta-markup language, used to create markup languages such as DocBook., GlossSeeAlso=[GML, XML]}, GlossSee=markup}}}}} 
+9
source

Wrap your card in a mute object as a container, for example:

 public class Country { private final Map<String,Map<String,Set<String>>> citiesAndCounties=new HashMap<>; // Generate getters and setters and see the magic happen. } 

The rest just works with your object mapper, like Object Mapper using the Joda module:

 public static final ObjectMapper JSON_MAPPER=new ObjectMapper(). disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES). setSerializationInclusion(JsonInclude.Include.NON_NULL). disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS). registerModule(new JodaModule()); // Calling your Object mapper JSON_MAPPER.writeValueAsString(new Country()); 

Hope this helps; -)

+1
source

Source: https://habr.com/ru/post/957603/


All Articles