Gson: Is there an easier way to serialize a map

前端 未结 5 2149
野趣味
野趣味 2020-11-28 04:36

This link from the Gson project seems to indicate that I would have to do something like the following for serializing a typed Map to JSON:

    public static         


        
5条回答
  •  情话喂你
    2020-11-28 05:19

    Only the TypeToken part is neccesary (when there are Generics involved).

    Map myMap = new HashMap();
    myMap.put("one", "hello");
    myMap.put("two", "world");
    
    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(myMap);
    
    System.out.println(json);
    
    Type typeOfHashMap = new TypeToken>() { }.getType();
    Map newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
    System.out.println(newMap.get("one"));
    System.out.println(newMap.get("two"));
    

    Output:

    {"two":"world","one":"hello"}
    hello
    world
    

提交回复
热议问题