如何在生成的 JSON 中使 \u 成为 \u?

问题描述 投票:0回答:1
public void run(String... args) throws Exception {
    final ObjectMapper jackson = new ObjectMapper();
    
    final ObjectNode objectNode = jackson.createObjectNode();
    String text = "Simplified Chinese 简体中文";
    
    final String escapedInUnicodeText = StringEscapeUtils.escapeJava(text);
    System.out.println(escapedInUnicodeText);
    //output is: Simplified Chinese \u7B80\u4F53\u4E2D\u6587
    
    objectNode.put("text", escapedInUnicodeText);
    System.out.println(jackson.writeValueAsString(objectNode));
    //output is  {"text":"Simplified Chinese \\u7B80\\u4F53\\u4E2D\\u6587"}
}

System.out.println(escapedInUnicodeText);
的结果是
Simplified Chinese \u7B80\u4F53\u4E2D\u6587

System.out.println(jackson.writeValueAsString(objectNode));
的结果是
{"text":"Simplified Chinese \\u7B80\\u4F53\\u4E2D\\u6587"}

关于第二个结果,生成的JSON,我怎样才能使

\\u
成为
\u

java json jackson
1个回答
0
投票

您可以使用 JsonGenerator.Feature.ESCAPE_NON_ASCII 功能,但也要确保您的字符串在序列化过程中不会双重转义。

为了实现这一点,您可以将 Jackson 配置为在序列化时不转义 Unicode 字符。这涉及使用 Jackson ObjectMapper 并自定义其序列化设置。

我会这样做:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.core.JsonGenerator;

public class UnicodeExample {
    public static void main(String[] args) throws Exception {
        // Create ObjectMapper with custom settings
        ObjectMapper mapper = new ObjectMapper();

        // Disable the default escaping for non-ASCII characters
        mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);

        // Example text with Unicode escapes
        String escapedInUnicodeText = "Simplified Chinese \u7B80\u4F53\u4E2D\u6587";
        
        // Create an ObjectNode and add the text
        ObjectNode objectNode = mapper.createObjectNode();
        objectNode.put("text", escapedInUnicodeText);
        
        // Serialize the object to JSON
        String jsonString = mapper.writeValueAsString(objectNode);

        // Output the result
        System.out.println(jsonString);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.