我有几个无法正确转换的字符串。我遇到的问题是,我所有的字符串上都有怪异的字符(它们是西班牙语,带有最高的重音符号),我能够使用以下代码将其转换:
与数据库的连接:连接后,我继续从数据库中获取信息,如下所示(它带有json格式),数据库信息显示为Perú:
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
//is.close();
Log.i("Tag:", result);
}
检索JSON列表:
try{
jArray = new JSONArray(welcome.result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "title:" + json_data.getString("title"));
try {
country = new String(json_data.getString("country").getBytes("ISO-8859-1"), "UTF-8");
}
catch (UnsupportedEncodingException e){
}
但是,我用西班牙语抓取了另一个字符串,它又恢复了原状,但其他字符串仍然可以正常显示。当前的字符串如下所示:PER。有什么想法吗?我猜正在使用不同的编码。我从中提取它们的数据库使用utf8_general_ci。先感谢您!
只需执行以下操作:
country = json_data.getString("country");
getString
已返回,String
因此无需对其进行编码ISO-8859-1
即可将其解码,但UTF-8
由于明显的原因而无法对其进行解码。
如果即使使用上面的代码也得到了不正确的字符,则意味着您的问题出在前面,可能是在解析JSON
内容时,它可能没有使用正确的字符编码来解析。
您需要将字符编码显式设置为,UTF-8
否则它将使用默认的编码:
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句