1 回答

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
一:解析普通json
1:不帶轉(zhuǎn)化字符
格式{"type":"ONLINE_SHIPS","message":{"currentTime":1400077615368,"direction":0,"id":1,"latitude":29.5506,"longitude":106.6466}}
JSONObject jsonObject = new JSONObject(jsonstr).getJSONObject("message");
System.out.println("currentTime:"+jsonObject.get("currentTime"));
System.out.println("direction:"+jsonObject.get("direction"));
System.out.println("latitude:"+jsonObject.get("latitude"));
System.out.println("longitude:"+jsonObject.get("longitude"));
jsonarray
JSONObject jo = ja.getJSONArray("cargoList").getJSONObject(0);
2:帶轉(zhuǎn)義字符的json格式
{"type":"ONLINE_SHIPS","message":"{\"currentTime\":1400077615368,\"direction\":0,\"id\":1,\"latitude\":29.5506,\"longitude\":106.6466}"}
其實(shí)也很簡(jiǎn)單,先把它轉(zhuǎn)化成字符串就可以了
JSONObject jsonObject = new JSONObject(jsonstr);
//先通過(guò)字符串的方式得到,轉(zhuǎn)義字符自然會(huì)被轉(zhuǎn)化掉
String jsonstrtemp = jsonObject.getString("message");
System.out.println("message:"+jsonstrtemp);
jsonObject = new JSONObject(jsonstrtemp);
System.out.println("currentTime:"+jsonObject.get("currentTime"));
System.out.println("direction:"+jsonObject.get("direction"));
System.out.println("latitude:"+jsonObject.get("latitude"));
System.out.println("longitude:"+jsonObject.get("longitude"));
二:遍歷Json對(duì)象
JSONObject ports = ja.getJSONObject("ports");
Iterator<String> keys = ports.keys();
while(keys.hasNext()){
String key=keys.next();
String value = ports.getString(key);
}
三:使用Gjson,json與對(duì)象相互轉(zhuǎn)化
使用Gson輕松將java對(duì)象轉(zhuǎn)化為json格式
String json = gson.toJson(Object);//得到j(luò)son形式的字符串
User user = gson.fromJson(json,User.class);//得到對(duì)象
- 1 回答
- 0 關(guān)注
- 761 瀏覽
添加回答
舉報(bào)