Gson和Map

public void parseToMap() {
    String json = "{\"age\":27,\"name\":\"lily\"}";
    Gson gson = new Gson();
    //方法一(推荐)
    Type type=new TypeToken>(){}.getType();
    Map map1=gson.fromJson(json,type);
    LogUtil.d("-->map is "+map1);
    //方法二
    Map map = new HashMap();
    map = (Map) gson.fromJson(json, map.getClass());
    LogUtil.d("-->map is "+map);
    //生成一个jsonString,可用map构造,无需创建新类
    Map personMap=new HashMap<>();
    personMap.put("age","27");
    personMap.put("name","lily");

    String mapJson=gson.toJson(personMap);

    LogUtil.d("-->mapJson is "+mapJson);

}

参考https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Generic-Types

QQ图片20170918114407.png

你可能感兴趣的:(Gson和Map)