用GSON踩過的坑
阿新 • • 發佈:2019-01-06
本來公司使用的是阿里的fastjson,後面轉換成了谷歌的json,GSON在轉換的風格上有所變化。
用fastjson,string轉json應該是:
String c = {“a”:"1","b":"2"};
JSONObject json = JSONObject.parseObject(c);
String a = json.getString("a");
用GSON:
String a = json.getString("a");
JsonObject jsonObject = GsonUtil.getParser().parse(c).getAsJsonObject();
String a = jsonObject.get("id").getAsString();
GSON map轉String
Map<String,String> map= new HashMap<>();
map.put("a","1");
map.put("b","2");
String c = GsonUtil.toJson(map);
GSON json轉類
先定義一個類:Dept
Dept dept= GsonUtil.getGson().fromJson(json, Dept.class);