码迷,mamicode.com
首页 > Web开发 > 详细

JSONString的转义和反转义

时间:2020-01-09 22:36:45      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:baidu   ppp   ack   rgs   col   alibaba   ejs   org   end   

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"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}

JSONString的转义和反转义

标签:baidu   ppp   ack   rgs   col   alibaba   ejs   org   end   

原文地址:https://www.cnblogs.com/yjh1995/p/12173720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!