Android Json串中添加转义符

Android Json串中添加转义符,第1张

一:解析普通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)//得到对象

转化成list

import java.util.List

import com.google.gson.Gson

import com.google.gson.reflect.TypeToken

import com.lc.function.Action

import com.lc.models.Groups

public class MapSearch {

private void ParseData(String _data)

{

Gson gson = new Gson()

List<Groups>ps = gson.fromJson(_data, new TypeToken<List<Groups>>(){}.getType())

System.out.println(ps.get(0).getGroup_name())

}

}

首先你的转义范围要先确定吧?

一般都是对中文、符号进行转义;

中文一般都是转成unicode;

如果数要转换成程序(JAVA)中直接使用的json字符串的话,一般都是在双引号前加\.

推荐给你一个json在线转义工具 网页链接 可以去看下。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/bake/11947666.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存