gpt4 book ai didi

java - 如何转换字符串中特殊字符的任何编码值并将其插入到java中的JSON对象中?

转载 作者:行者123 更新时间:2023-12-01 18:54:02 25 4
gpt4 key购买 nike

我正在尝试将货币符号(例如欧元)插入到 java 中的 JSON 对象中。我有欧元的编码字符串(\u20AC。我们可能有各种其他符号,\t,还有其他符号)。当我尝试使用普通字符串变量时,它会自动转换为欧元符号和制表符空间,但是当我将其插入 JSON 对象时,它不会转换。我尝试使用 java.net.URLDecoder.decode() 方法,但它也不起作用。

    String s1 = "pqr\u20ACab\tcd";

JSONObject temp = new JSONObject();
temp.put("field", java.net.URLDecoder.decode(s1));
System.out.println(s1);
System.out.println(temp);

下面是我得到的输出

   pqr€ab   cd
{"field":"pqr\u20ACab\tcd"}

最佳答案

我不确定您的具体要求,但为了解决上述情况。

ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");
temp.write(writer);
writer.flush();
String jsonString = new String(out.toByteArray(),"utf-8");
JSONObject newJSON = new JSONObject(jsonString);
String newJsonString = newJSON.getString("field");
System.out.println(newJsonString );

关于java - 如何转换字符串中特殊字符的任何编码值并将其插入到java中的JSON对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692250/

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