有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图在java中的JSON对象中插入一个货币符号(例如欧元)。我有欧元的编码字符串(\u20AC。我们可能有各种其他符号、\t和其他符号)。当我尝试使用普通字符串变量时,它会自动转换为欧元符号和制表符空间,但当我将其插入JSON对象时,它不会转换。我试着用java。网URL解码器。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"}

共 (2) 个答案

  1. # 1 楼答案

    我不知道你的确切要求,但解决上述情况

    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 );
    
  2. # 2 楼答案

    com。谷歌。格森。JsonParser取消了欧元符号:

        String s1 = "pqr\u20ACab\tcd";
        JSONObject temp = new JSONObject();
        temp.put("field", s1);
        System.out.println(JsonParser.parseString(String.valueOf(temp)));
    

    此打印{“字段”:“pqr€ab\tcd”}