Library to encode/decode from json to java.util.Map?

后端 未结 6 1703
野趣味
野趣味 2020-12-05 05:44

Does anyone knows a java library that could easily encode java Maps into json objects and the other way around?

UPDATE

For reasons couldn\'

6条回答
  •  春和景丽
    2020-12-05 06:26

    You can use Google Gson for that. It has excellent support for Generic types.

    Here's an SSCCE:

    package com.stackoverflow.q2496494;
    
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    import com.google.gson.Gson;
    import com.google.gson.reflect.TypeToken;
    
    public class Test {
    
       public static void main(String... args) {
            Map map = new LinkedHashMap();
            map.put("key1", "value1");
            map.put("key2", "value2");
            map.put("key3", "value3");
            Gson gson = new Gson();
    
            // Serialize.
            String json = gson.toJson(map);
            System.out.println(json); // {"key1":"value1","key2":"value2","key3":"value3"}
    
            // Deserialize.
            Map map2 = gson.fromJson(json, new TypeToken>() {}.getType());
            System.out.println(map2); // {key1=value1, key2=value2, key3=value3}
        }
    
    }
    

提交回复
热议问题