【问题标题】:Using Hebrew on JSON code?在 JSON 代码上使用希伯来语?
【发布时间】:2014-02-20 15:09:14
【问题描述】:

我正在使用此代码从 MySQL 数据库 POST 和 GET 数据。 但是,当获取非英文数据时,它会显示为问号? 我要进行哪些更改才能启用希伯来语语言?

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {

}

public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
    try {

        if(method == "POST"){

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;

}

}

【问题讨论】:

  • 永远不要使用method == "POST",始终使用method.equals("POST")进行字符串比较。
  • ... new InputStreamReader(is, "iso-8859-1") 你在这里使用的不是 unicode 编码,而是 Latin-1,它不支持希伯来字符。
  • 您应该考虑使用比 org.json 更可靠的 API -- 例如 Jackson
  • skiwi,谢谢你说的...
  • Thomas,我应该用什么来支持希伯来语?

标签: java mysql json character-encoding hebrew


【解决方案1】:

确保您的 HTTP 响应以 Unicode(例如 UTF-8)编码,并且您的客户端(使用服务的应用程序)必须知道该编码以读取您的响应。

【讨论】:

  • 嗯,JSON 需要 UTF-8 或 UTF-{16,32}。并非所有 Unicode 编码都受支持。
  • ... 这意味着接受字符串作为输入而不是纯字节流的库有点损坏。库应该发现字节流是否包含 UTF-8、UTF-16 或 UTF-32 大端或小端并处理任何一个。
猜你喜欢
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多