gpt4 book ai didi

java - 通过 JSONObject 传递 Unicode 字符串时出错

转载 作者:行者123 更新时间:2023-11-30 08:08:52 26 4
gpt4 key购买 nike

我必须将 unicode 字符串传递给 JSONObject。

JSONObject json = new JSONObject("{\"One\":\"\\ud83c\\udf45\\ud83c\\udf46\"}");
json.put("Two", "\ud83c\udf45\ud83c\udf46");
System.out.println(json.toString());

但我有这个:

{"One":"🍅🍆","Two":"🍅🍆"}

我想要这个:

{"One":"\ud83c\udf45\ud83c\udf46","Two":"\ud83c\udf45\ud83c\udf46"}

最佳答案

系统正在按设计运行。您只是没有考虑到 JSON 并不要求大多数 Unicode 字符采用 \uXXXX 格式。某些转义字符必须采用\X格式,控制字符<= 0x1F必须采用\uXXXX格式,但任何其他字符可以采用\uXXXX格式,但不要求。您显示的字符不属于这些范围,这就是为什么 toString() 没有将它们编码为 \uXXXX 格式。

当您调用 new JSONObject(String) 时,它会将输入字符串解码为实际的 Unicode 字符串,就像您已执行此操作一样:

JSONObject json = new JSONObject();
json.put("One", "\ud83c\udf45\ud83c\udf46");

这完全没问题。您希望JSONObject在内部保存未转义的Unicode数据。

您遇到的问题是 JSONObject.toString() 没有将您的特定 Unicode 字符格式化为 \uXXXX 格式。这是完全有效的 JSON,但不是您希望的格式(为什么您希望它们采用这种格式?)。

查看 Java 的 JSONStringer 类(实现 JSONObject.toString())的源代码可以发现,它仅格式化 <= 0x1F 中的非保留控制字符 \uXXXX 格式,其他非保留字符按原样格式化。这符合JSON规范。

要执行您所要求的操作,您必须在调用 JSONObject.toString() 正常格式化保留字符和 ASCII 字符后,根据需要手动格式化 Unicode 字符,例如:

JSONObject json = new JSONObject("{\"One\":\"\\ud83c\\udf45\\ud83c\\udf46\"}");
// decodes as if json.put("One", "\ud83c\udf45\ud83c\udf46")
// or json.put("One", "🍅🍆") were called directly ...

json.put("Two", "\ud83c\udf45\ud83c\udf46");
// same as calling json.put("Two", "🍅🍆") ...

String s = json.toString();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i)
{
char ch = s.charAt(i);
if (ch >= 0x7F)
sb.append(String.format("\\u%04x", (int) ch));
else
sb.append(ch);
}

System.out.println(sb.toString());
// outputs '{"One":"\ud83c\udf45\ud83c\udf46","Two":"\ud83c\udf45\ud83c\udf46"}' as expected ...

关于java - 通过 JSONObject 传递 Unicode 字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com