Java 你能避免 Gson 将 "<" 和 ">" 转换成 unicode 转义序列吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4147012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:04:40  来源:igfitidea点击:

Can you avoid Gson converting "<" and ">" into unicode escape sequences?

javajsongson

提问by Jonik

I noticed that Gsonconverts the string "<" into an unicode escape sequence in JSON output. Can you avoid this somehow, or do characters like "<" and ">" always have to be escaped in JSON?

我注意到Gson将字符串“<”转换为 JSON 输出中的 unicode 转义序列。你能以某种方式避免这种情况吗,或者像“<”和“>”这样的字符总是必须在 JSON 中转义?

Consider this example which prints {"s":"\u003c"}; I'd want simply {"s":"<"}.

考虑这个打印的例子{"s":"\u003c"};我只想 {"s":"<"}.

public static void main(String[] args) {
    Gson gson = new GsonBuilder().create();
    System.out.println(gson.toJson(new Foo()));  
}

static class Foo {
    String s = "<";
}

Context: the piece of JSON I'm creating has nothing to do with HTML pages or even JavaScript; it's just used to pass certain structured information to another piece of software (embedded in a device, written in C).

上下文:我创建的 JSON 片段与 HTML 页面甚至 JavaScript 无关;它只是用来将某些结构化信息传递给另一个软件(嵌入在设备中,用 C 编写)。

采纳答案by BalusC

You need to disable HTML escaping.

您需要禁用 HTML 转义

Gson gson = new GsonBuilder().disableHtmlEscaping().create();