jar包
<!-- 已过时 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- JSON等格式的转义和反转义 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
代码
import com.alibaba.fastjson.JSON;
import org.apache.commons.text.StringEscapeUtils;
import utils.FileUtil;
/**
* JSON等字符格式的转义和反转义
*/
public class EscapeTest {
public static void main(String[] args) {
String str = FileUtil.readCsv("E:\\IdeaProjects\\javaStudy\\src\\test\\data\\capability.json");
System.out.println("读取的文件String:\n"+str);
str= JSON.parseObject(str).toJSONString();
System.out.println("转换为JSONString:\n"+str);
//转义
str= StringEscapeUtils.escapeJson(str);
System.out.println("转义后的JSONString:\n"+str);
//反转义
str=StringEscapeUtils.unescapeJson(str);
System.out.println("反转义后的JSONString:\n"+str);
}
}
打印内容
读取的文件String:
{
"platformName": "Android",
"platformVersion": "6.0.1",
"deviceName": "127.0.0.1:7555",
"appPackage": "com.baidu.tieba",
"appActivity": ".tblauncher.MainTabActivity",
"noReset": true,
"unicodeKeyboard": true,
"resetKeyboard": true
}
转换为JSONString:
{"appPackage":"com.baidu.tieba","appActivity":".tblauncher.MainTabActivity","noReset":true,"platformVersion":"6.0.1","unicodeKeyboard":true,"platformName":"Android","deviceName":"127.0.0.1:7555","resetKeyboard":true}
转义后的JSONString:
{\"appPackage\":\"com.baidu.tieba\",\"appActivity\":\".tblauncher.MainTabActivity\",\"noReset\":true,\"platformVersion\":\"6.0.1\",\"unicodeKeyboard\":true,\"platformName\":\"Android\",\"deviceName\":\"127.0.0.1:7555\",\"resetKeyboard\":true}
反转义后的JSONString:
{"appPackage":"com.baidu.tieba","appActivity":".tblauncher.MainTabActivity","noReset":true,"platformVersion":"6.0.1","unicodeKeyboard":true,"platformName":"Android","deviceName":"127.0.0.1:7555","resetKeyboard":true}