Gson to HashMap

后端 未结 3 907
一个人的身影
一个人的身影 2020-12-12 23:46

Is there a way to convert a String containing json to a HashMap, where every key is a json-key and the value is the value of the json-key? The json has no nested values. I a

相关标签:
3条回答
  • 2020-12-13 00:26

    Use TypeToken, as per the GSON FAQ:

    Gson gson = new Gson();
    Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
    Map<String,String> map = gson.fromJson(json, stringStringMap);
    

    No casting. No unnecessary object creation.

    0 讨论(0)
  • 2020-12-13 00:30

    I like:

    private static class MyMap extends HashMap<String,String> {};
    ...
    MyMap map = gson.fromJson(json, MyMap.class);
    
    0 讨论(0)
  • 2020-12-13 00:35

    If I use the TypeToken solution with a Map<Enum, Object> I get "duplicate key: null".

    The best solution for me is:

    String json = "{\"id\":3,\"location\":\"NewYork\"}";
    Gson gson = new Gson();
    Map<String, Object> map = new HashMap<String, Object>();
    map = (Map<String, Object>)gson.fromJson(json, map.getClass());
    

    Result:

    {id=3.0, location=NewYork}
    
    0 讨论(0)
提交回复
热议问题