【发布时间】:2023-03-23 10:07:01
【问题描述】:
我发现在数据库中的某些搜索结果存在问题。当某些字段有额外的字符(如“ü”)时,该字段返回为 null,因此在搜索中显示为 null。我的代码是这样的: php脚本
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%".$_REQUEST['search']."%'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
JSON PARSER 构造函数:
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONArray getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
JSONArray jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
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();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
//json_data = new JSONObject(result);
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return jArray;
}
}
有什么办法可以解决这个问题吗?
更新:只要我不能用 JSON 传递它,因为它只接受 UTF-8 字符。我认为一种可能的解决方案是通过 PHP 将文本转换为 UTF-8 编码存档,另一种是使用支持其他编码的 JSON 的替代方案。所以我想尝试第一个。因此,如果有人知道使用 PHP 将文本编码转换为 UTF-8 的好算法将有所帮助。也欢迎其他提示或提示找到解决方案的可能方向请评论这篇文章欢迎任何想法
已解决 我解决了它编码为 UTF-8 的问题,它将我的字符(如“ü”)更改为类似 u\000f 的字符,但是当它显示在屏幕上时,java 编辑器将其显示为 iso-8859-1,如 Ü。修改后的 PHP 代码在查询后有以下几行:
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%$search1%'");
while($e=mysql_fetch_assoc($q)){
$e['ARTI'] = utf8_encode ( $e['ARTI'] );
$e['DESC'] = utf8_encode ( $e['DESC'] );
$e['PRESENT'] = utf8_encode ( $e['PRESENT'] );
$output[]=$e;
}
print(json_encode($output));
【问题讨论】: