【发布时间】:2016-05-25 21:59:56
【问题描述】:
我正在使用这个 PHP 代码从 MySQL 数据库生成 JSON:
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = array_map('utf8_encode', $row);
}
echo json_encode($emparray);
然后我使用 HttpUrlConnection 来获取 url 并获取 Echo 字符串:
URL url = new URL("http://localhost/myserver.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
打印的是:
[{"id":"1","titulo":"C\u00f3digo de Defesa do Consumidor","descricao":"Institui o c\u00f3digo de defesa do consumidor","tags":"cdc","categorias":"cat_cod,cat_leisord","numero_da_lei":"13105","data_da_lei":"11111111","ativa":"1","byuser":"0","versao_da_lei":"0","url":"http:\/\/www.planalto.gov.br\/ccivil_03\/leis\/L8078compilado.htm"}]
我知道输出是编码的,因为我有$emparray[] = array_map('utf8_encode', $row);,但如果我不使用它,具有特殊字符的文本将变为 NULL。
如何转换
"titulo":"C\u00f3digo de Defesa do Consumidor"
到
"titulo":"Código de Defesa do Consumidor"
我试过了:
new String(result.getBytes(), "UTF-8");
但没有任何改变
【问题讨论】:
-
尝试将
myserver.php的标题设置为header('Content-Type: application/json;charset=utf-8');将此行写在顶部(第一行) -
如何使用
mysql_set_charset或mysqli::set_charset将UTF-8 设置为所有MySQL 连接的默认字符集? -
不要使用 utf8 编码器/解码器。而是到处都有 utf8。 “unicode”
\u00f3是从哪里来的?在此之前返回并将其更改为“utf8”。
标签: php android mysql json utf-8