使用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\":\"20200518\",\"project\":{\"name\":\"zhangsan\",\"age\":\"25\"},\"content\":{\"distinct_id\":\"51818968\",\"event\":\"AppClick\",\"properties\":{\"element_page\":\"新闻列表页\",\"screen_width\":\"640\",\"app_version\":\"1.0\",\"os\":\"GNU/Linux\",\"battery_level\":\"11\",\"device_id\":\"886113235750\",\"client_time\":\"2020-05-18 13:53:56\",\"ip\":\"61.233.88.41\",\"is_charging\":\"1\",\"manufacturer\":\"Apple\",\"carrier\":\"中国电信\",\"screen_height\":\"320\",\"imei\":\"886113235750\",\"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":"20200518","project":"{\"name\":\"zhangsan\",\"age\":\"25\"}","content":{"distinct_id":"51818968","event":"AppClick","properties":{"element_page":"新闻列表页","screen_width":"640","app_version":"1.0","os":"GNU/Linux","battery_level":"11","device_id":"886113235750","client_time":"2020-05-18 13:53:56","ip":"61.233.88.41","is_charging":"1","manufacturer":"Apple","carrier":"中国电信","screen_height":"320","imei":"886113235750","model":"","network_type":"WIFI","element_name":"tag"}}}
经过测试,如果单独输出字符串是不会有反斜杠的,只是将使用不同方法解析出来的字符串放入JSON对象中时,当值为json字符串时会出现反斜杠。
例如上面的
System.out.println(metaJson.getString("project")); // {"name":"zhangsan","age":"25"}
System.out.println(metaJson.getString("content")); // {"distinct_id":"51818968","event":"AppClick","properties":{"element_page":"新闻列表页","screen_width":"640","app_version":"1.0","os":"GNU/Linux","battery_level":"11","device_id":"886113235750","client_time":"2020-05-18 13:53:56","ip":"61.233.88.41","is_charging":"1","manufacturer":"Apple","carrier":"中国电信","screen_height":"320","imei":"886113235750","model":"","network_type":"WIFI","element_name":"tag"}}
从以上代码可以看到将json字符串解析出来再次放入json对象中时出现反斜杠,可以使用
JSONPath.eval(JSONObject对象,key)