Convert JSONObject to Map

后端 未结 6 1896
抹茶落季
抹茶落季 2020-12-08 18:20

I have a JSONObject with some attributes that I want to convert into a Map

Is there something that I can use from the

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 18:50

    Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.

    Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).

    If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:

    ObjectMapper mapper = new ObjectMapper();
    TypeFactory typeFactory = mapper.getTypeFactory();
    MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
    HashMap map = mapper.readValue(new StringReader(hashTable.toString()), mapType);
    

提交回复
热议问题