将字符串转换为JSONObject并返回字符串,而不会丢失UTF-8编码

时间:2019-01-24 08:00:55

标签: java utf-8

我在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个Unicode字符):

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 个答案:

答案 0 :(得分:1)

由于toString的实现方式,您看到了Unicode转义序列。可以通过这种方式来实现它,以弄清楚字符串中包含哪些字符,从而使调试代码变得更加容易,因为有时不同的代码点看起来可能非常相似。

实际字符串仍未转义。在数组中打印单个字符串将不会显示转义序列:

System.out.println(resultJSON.getJSONObject("result").getJSONObject("opening_hours").getJSONArray("weekday_text").getString(0));

答案 1 :(得分:0)

您可以使用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");