【问题标题】:Converting encoded utf-8 JSON转换编码的 utf-8 JSON
【发布时间】: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_charsetmysqli::set_charset 将UTF-8 设置为所有MySQL 连接的默认字符集?
  • UTF-8 all the way through的可能重复
  • 不要使用 utf8 编码器/解码器。而是到处都有 utf8。 “unicode”\u00f3 是从哪里来的?在此之前返回并将其更改为“utf8”。

标签: php android mysql json utf-8


【解决方案1】:

您可以使用 StringEscapeUtils Apache 库 https://commons.apache.org/proper/commons-lang/download_lang.cgi

为了将 unicodes 保存在数据库中,您必须对其进行编码。因此,通过编码将您的 unicodes 发送到服务器

StringEscapeUtils.escapeJava("Código de Defesa do Consumidor")

用于在android中显示编码的unicode

StringEscapeUtils.unescapeJava("C\u00f3digo de Defesa do Consumidor")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-18
    • 2012-06-30
    • 2011-06-26
    • 1970-01-01
    • 2014-02-02
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多