杰瑞科技汇

Java如何去除JSON转义符?

在Java中去掉JSON中的转义符

在Java中处理JSON数据时,有时需要去掉字符串中的转义符(如\n, \t, \"等),以下是几种常见的方法:

方法1:使用String的replace方法

String jsonWithEscapes = "{\"name\":\"John\\nDoe\",\"age\":30}";
String jsonWithoutEscapes = jsonWithEscapes.replace("\\n", "\n")
                                          .replace("\\t", "\t")
                                          .replace("\\\"", "\"")
                                          .replace("\\\\", "\\");
System.out.println(jsonWithoutEscapes);

方法2:使用正则表达式

import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class JsonEscapeRemover {
    public static String removeEscapes(String json) {
        // 处理常见的转义序列
        json = json.replace("\\n", "\n");
        json = json.replace("\\t", "\t");
        json = json.replace("\\r", "\r");
        json = json.replace("\\\"", "\"");
        json = json.replace("\\\\", "\\");
        json = json.replace("\\/", "/");
        // 处理Unicode转义序列
        Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher(json);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String unicodeValue = matcher.group(1);
            char unicodeChar = (char) Integer.parseInt(unicodeValue, 16);
            matcher.appendReplacement(sb, String.valueOf(unicodeChar));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}

方法3:使用Jackson库

如果你使用Jackson库处理JSON,可以配置ObjectMapper来不转义特殊字符:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(SerializationFeature.ESCAPE_NON_ASCII);
// 使用这个mapper处理JSON时,不会自动转义非ASCII字符

方法4:使用Gson库

使用Gson时,可以配置GsonBuilder来控制转义:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder()
    .disableHtmlEscaping()
    .create();
// 使用这个gson处理JSON时,不会进行HTML转义

注意事项

  1. 直接去掉转义符可能会改变JSON的结构和含义,确保你的操作是安全的
  2. 对于Unicode转义序列(如\u0041),需要特殊处理
  3. 如果JSON是从外部来源获取的,考虑使用专门的JSON库(如Jackson或Gson)来解析,而不是手动处理转义符

完整示例

public class JsonEscapeRemover {
    public static void main(String[] args) {
        String jsonWithEscapes = "{\"name\":\"John\\nDoe\",\"age\":30,\"address\":\"123\\tMain St\\\"\"}";
        // 方法1:简单替换
        String simpleResult = jsonWithEscapes.replace("\\n", "\n")
                                          .replace("\\t", "\t")
                                          .replace("\\\"", "\"")
                                          .replace("\\\\", "\\");
        System.out.println("简单替换结果:");
        System.out.println(simpleResult);
        // 方法2:正则表达式处理
        String regexResult = removeEscapes(jsonWithEscapes);
        System.out.println("\n正则表达式处理结果:");
        System.out.println(regexResult);
    }
    public static String removeEscapes(String json) {
        // 处理常见的转义序列
        json = json.replace("\\n", "\n");
        json = json.replace("\\t", "\t");
        json = json.replace("\\r", "\r");
        json = json.replace("\\\"", "\"");
        json = json.replace("\\\\", "\\");
        json = json.replace("\\/", "/");
        // 处理Unicode转义序列
        Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher(json);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String unicodeValue = matcher.group(1);
            char unicodeChar = (char) Integer.parseInt(unicodeValue, 16);
            matcher.appendReplacement(sb, String.valueOf(unicodeChar));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}

选择哪种方法取决于你的具体需求和JSON数据的复杂性,对于简单的JSON,方法1可能就足够了;对于更复杂的情况,方法2或使用专门的JSON库会更合适。

分享:
扫描分享到社交APP
上一篇
下一篇