0

I'm using this PHP code to generate the JSON from MySQL database:

    while($row =mysqli_fetch_assoc($result))
        {
$emparray[] = array_map('utf8_encode', $row);
        }
        echo json_encode($emparray);

Then I use the HttpUrlConnection to fetch the url and get the Echo string:

  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);
            }

the print is:

[{"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"}]

I know that the output is encoded because I have $emparray[] = array_map('utf8_encode', $row); but if I do not use this, the text that has special chars becomes NULL.

How can I convert

"titulo":"C\u00f3digo de Defesa do Consumidor"

to

"titulo":"Código de Defesa do Consumidor"

I've tried:

 new String(result.getBytes(), "UTF-8");

but nothing changed

user1219801
  • 169
  • 4
  • 17
user2582318
  • 1,607
  • 5
  • 29
  • 47
  • try set header of your `myserver.php` as `header('Content-Type: application/json;charset=utf-8');` write this line at top (first line) – Akam May 25 '16 at 22:06
  • How about using `mysql_set_charset` or `mysqli::set_charset` to set UTF-8 as the default character set for all MySQL connections? – user1219801 May 25 '16 at 22:13
  • Possible duplicate of [UTF-8 all the way through](http://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – Rick James Jun 01 '16 at 19:05
  • Don't use utf8 encoders/decoders. Instead have utf8 everywhere. Where did "unicode" `\u00f3` come from? Go back before that and change it to be "utf8". – Rick James Jun 01 '16 at 19:07

1 Answers1

0

You can use StringEscapeUtils Apache Library https://commons.apache.org/proper/commons-lang/download_lang.cgi

For saving the unicodes in database you have to encode them. So send your unicodes to server by encoding like

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

For displaying the encoded unicode in android

StringEscapeUtils.unescapeJava("C\u00f3digo de Defesa do Consumidor")
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46