使用fastJson导入的pom依赖
<dependency> <groupId>com.alibaba
groupId> <artifactId>fastjson
artifactId> <version>1.2.68
version> <scope>compile
scope>
dependency>
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; public class B64InterceptorTest {
public static void main(String[] args) {
//json字符串 String str = "{\"ctime\":\"\",\"project\":{\"name\":\"zhangsan\",\"age\":\"25\"},\"content\":{\"distinct_id\":\"\",\"event\":\"AppClick\",\"properties\":{\"element_page\":\"新闻列表页\",\"screen_width\":\"640\",\"app_version\":\"1.0\",\"os\":\"GNU/Linux\",\"battery_level\":\"11\",\"device_id\":\"0\",\"client_time\":\"2020-05-18 13:53:56\",\"ip\":\"61.233.88.41\",\"is_charging\":\"1\",\"manufacturer\":\"Apple\",\"carrier\":\"中国电信\",\"screen_height\":\"320\",\"imei\":\"0\",\"model\":\"\",\"network_type\":\"WIFI\",\"element_name\":\"tag\"}}}\n"; //将json字符串解析为json对象 JSONObject metaJson = JSONObject.parseObject(str); JSONObject jsonObject = new JSONObject(); //当值为单个字符串时,使用JSONObject对象.getString(key)方法,json对象输出时没有反斜杠 jsonObject.put("ctime", metaJson.getString("ctime")); //当值为json字符串时,使用JSONObject对象.getString(key)方法,json对象输出时带有反斜杠 jsonObject.put("project", metaJson.getString("project")); //当值为json字符串时,使用JSONPath.eval(JSONObject对象,key),json对象输出时没有反斜杠, jsonObject.put("content", JSONPath.eval(metaJson, "content")); System.out.println(jsonObject.toString()); } } //输出的值为 {
"ctime":"","project":"{\"name\":\"zhangsan\",\"age\":\"25\"}","content":{
"distinct_id":"","event":"AppClick","properties":{
"element_page":"新闻列表页","screen_width":"640","app_version":"1.0","os":"GNU/Linux","battery_level":"11","device_id":"0","client_time":"2020-05-18 13:53:56","ip":"61.233.88.41","is_charging":"1","manufacturer":"Apple","carrier":"中国电信","screen_height":"320","imei":"0","model":"","network_type":"WIFI","element_name":"tag"}}}
System.out.println(metaJson.getString("project")); // {"name":"zhangsan","age":"25"} System.out.println(metaJson.getString("content")); // {"distinct_id":"","event":"AppClick","properties":{"element_page":"新闻列表页","screen_width":"640","app_version":"1.0","os":"GNU/Linux","battery_level":"11","device_id":"0","client_time":"2020-05-18 13:53:56","ip":"61.233.88.41","is_charging":"1","manufacturer":"Apple","carrier":"中国电信","screen_height":"320","imei":"0","model":"","network_type":"WIFI","element_name":"tag"}}
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/218666.html原文链接:https://javaforall.net
