【问题标题】:After json parse i have symbols instead lettersjson解析后我有符号而不是字母
【发布时间】:2014-08-20 14:31:32
【问题描述】:

英文文本和数字正确显示在结果字符串中,但我希望显示的其他字母不是。取而代之的是一系列符号,例如 &-#-1080; ... 我试图在我的 InputStreamReader 上设置 UTF-8,但它没有效果。感谢任何帮助。 代码如下:

public class HttpClient {
private static String BASE_URL = "here url";
public String getData(String number) {
    HttpURLConnection con = null ;
    InputStream is = null;
    try {
        con = (HttpURLConnection) ( new URL(BASE_URL + number)).openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();
        // Let's read the response
        StringBuffer buffer = new StringBuffer();
        is = con.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        String line = null;
        while (  (line = br.readLine()) != null )
            buffer.append(line + "\r\n");

        is.close();
        con.disconnect();
        return buffer.toString();
    }
    catch(Throwable t) {
        t.printStackTrace();
    }
    finally {
        try { is.close(); } catch(Throwable t) {}
            try { con.disconnect(); } catch(Throwable t) {}
        }
        return null;
    }
}

------------
JSONObject jb = new JSONObject(data);
JSONArray jr = jb.getJSONArray("items");
JSONObject c = jr.getJSONObject(0);
String id = c.getString(TAG_ID);
String images = c.getString(TAG_IMAGES);
String title = new String(c.getString(TAG_TITLE).getBytes("ISO-8859-1"), "UTF-     8");//tried this - didn't help
String text = c.getString(TAG_TEXT);`

【问题讨论】:

  • 来自服务的响应是 UTF-8
  • 谢谢,使用 unescapeHtml3 函数将这个符号串起来解决了这个问题。链接:stackoverflow.com/questions/994331/…
  • 找到了一个更新更好的方法:Html.fromHtml(),效果很好

标签: java json parsing utf-8 encode


【解决方案1】:

您确定响应是 UTF-8 吗?

尝试在浏览器中点击 URL 并查看 HTTP 响应标头,我猜它不是 UTF-8。

有许多库可以帮助处理 Web 服务请求。更底层的库之一是http-client。我建议你使用这个(或更高级别的抽象)而不是直接使用 HttpURLConnection。

【讨论】:

    【解决方案2】:

    如果您从 php Web 服务创建 json,请使用此代码

    echo utf8_encode(json_encode($result));
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2020-09-28
      相关资源
      最近更新 更多