为了账号安全,请及时绑定邮箱和手机立即绑定

java Json 串中的转义字符?

java Json 串中的转义字符?

慕容森 2018-12-20 23:11:57
java Json 串中的转义字符
查看完整描述

1 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

一:解析普通json
1:不带转化字符
格式{"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:带转义字符的json格式
{"type":"ONLINE_SHIPS","message":"{\"currentTime\":1400077615368,\"direction\":0,\"id\":1,\"latitude\":29.5506,\"longitude\":106.6466}"}
其实也很简单,先把它转化成字符串就可以了

JSONObject jsonObject = new JSONObject(jsonstr);
//先通过字符串的方式得到,转义字符自然会被转化掉
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对象

JSONObject ports = ja.getJSONObject("ports");
Iterator<String> keys = ports.keys();
while(keys.hasNext()){
String key=keys.next();
String value = ports.getString(key);
}

三:使用Gjson,json与对象相互转化
使用Gson轻松将java对象转化为json格式
String json = gson.toJson(Object);//得到json形式的字符串
User user = gson.fromJson(json,User.class);//得到对象

 


查看完整回答
反对 回复 2019-01-11
  • 1 回答
  • 0 关注
  • 665 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信