Nested Json to Map using Jackson

前端 未结 2 1532
悲哀的现实
悲哀的现实 2021-01-05 11:31

I\'m trying to dynamically parse some JSON to a Map. The following works well with simple JSON

        String easyString = \"{\\\"name\\\":\\\"mkyong\\\", \         


        
相关标签:
2条回答
  • 2021-01-05 12:09

    Wrap your Map into a dumb object as container, like this:

    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 is just working with your Object mapper, example Object mapper using 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 that helps ;-)

    0 讨论(0)
  • 2021-01-05 12:18

    I think the error occurs because the minute Jackson encounters the { character, it treats the remaining content as a new object, not a string. Try Object as 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}}}}}
    
    0 讨论(0)
提交回复
热议问题