代码之家  ›  专栏  ›  技术社区  ›  Giorgos Myrianthous

字符串到JSONObject并返回到字符串,而不丢失UTF-8编码

  •  0
  • Giorgos Myrianthous  · 技术社区  · 7 年前

    我有以下几点 result String

    {
       "html_attributions" : [],
       "result" : {
          "opening_hours" : {
             "open_now" : true,
             "weekday_text" : [
                "Monday: 8:00 AM – 7:00 PM",
                "Tuesday: 8:00 AM – 7:00 PM",
                "Wednesday: 8:00 AM – 2:30 PM",
                "Thursday: 8:00 AM – 7:00 PM",
                "Friday: 8:00 AM – 7:30 PM",
                "Saturday: 8:00 AM – 6:00 PM",
                "Sunday: Closed"
             ]
          }
       },
       "status" : "OK"
    }
    

    我把它转换成 JSONObject 使用

    JSONObject resultJSON = new JSONObject(result);
    

    weekday_text 键,但似乎最终输出不在 UTF-8 \u2013

    System.out.println(resultJSON.getJSONObject("result").getJSONObject("opening_hours").getJSONArray("weekday_text").toString());
    
    ["Monday: 8:00 AM \u2013 7:00 PM","Tuesday: 8:00 AM \u2013 7:00 PM","Wednesday: 8:00 AM \u2013 2:30 PM","Thursday: 8:00 AM \u2013 7:00 PM","Friday: 8:00 AM \u2013 7:30 PM","Saturday: 8:00 AM \u2013 6:00 PM","Sunday: Closed"]
    

    我错过了什么?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sweeper    7 年前

    您看到unicode转义序列是因为 toString

    实际的字符串仍然没有被替换。在数组中打印单个字符串不会显示转义序列:

    System.out.println(resultJSON.getJSONObject("result").getJSONObject("opening_hours").getJSONArray("weekday_text").getString(0));
    
        2
  •  0
  •   fstam    7 年前

    您可以使用OutputStreamWriter来管理输出编码。

    JSONObject resultJSON = new JSONObject(result);    
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");
    resultJSON.write(writer);
    writer.flush();
    
    String jSONStringUTF8 = new String(out.toByteArray(),"utf-8");
    JSONObject newJSON = new JSONObject(jSONStringUTF8);
    String value = newJSON.getString("content");
    
    推荐文章