java resolves the php function json_encode unicode encoding problem

  • 2020-05-10 18:03:55
  • OfStack

During the development of android, there is a coding problem when connecting with the server-side interface. The data obtained from the server-side is   "\u8bbe\u59071ID-\u8bbe\u59071\u540d\u79f0; \ u8bbe \ u59073id - \ u8bbe \ u59073 \ u540d \ u79f0; \ u8bbe \ u59077id - \ u8bbe \ u59077 \ u540d \ u79f0 "interface is by json_encode php function returned after coding, on the client side through java. net. URLdecoder. decode () decoding, However, directly copying the above strings into decode() method can be decoded normally, and the received strings are not used after encoding utf-8. Finally, relevant information is searched on the Internet to find a solution.

1, json_encode function:

json_encode   --   encodes the variable JSON.

string   json_encode   ($value  ), return   JSON form of   value   value.

Parameter:   value   to be encoded can be any data type except the resource   type

        this function can only accept data encoded by UTF-8

Return value: a   string   in JSON form is returned on success of encoding.

2. The client is decoded in java:

The first way


public String unescapeUnicode(String str){
  StringBuffer b=new StringBuffer();
  Matcher m = Pattern.compile("\\\\u([0-9a-fA-F]{4})").matcher(str);
  while(m.find())
   b.append((char)Integer.parseInt(m.group(1),16));
  return b.toString();
 }

Simply use the unescapeUnicode() method to decode.

2. Parse using json_simple.jar package

Download address: https: / / www ofstack. com softs / 455885. html

JSON.simple is a simple Java class library for parsing and generating JSON text. Independent of other libraries, high performance.


Object obj=JSONValue.parse(jsonStr);return obj.toString();


  PHP server-side solutions:


<html>
<head><meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>php generate  json  Chinese </title>
<?php 
 
function arrayRecursive(&$array, $function, $apply_to_keys_also = false) 
{ 
 static $recursive_counter = 0; 
 
 if (++$recursive_counter > 1000) 
 { 
   die('possible deep recursion attack'); 
 } 
 
 foreach ($array as $key => $value) 
 { 
 
  if (is_array($value)) 
  { 
   //arrayRecursive($array[$key], $function, $apply_to_keys_also); 
  } 
  else
  { 
   $array[$key] = $function($value);
  } 
 
  if ($apply_to_keys_also && is_string($key)) 
  { 
   $new_key = $function($key); 
 
   if ($new_key != $key) 
   { 
    $array[$new_key] = $array[$key]; 
    unset($array[$key]); 
   } 
  } 
 }
 $recursive_counter--; 
} 
 
function JSON($array) 
{ 
 //arrayRecursive($array, 'urlencode', true); 
 //print_r($array);
 $json = json_encode($array); 
 return urldecode($json); 
} 
 
$array = array
  ( 
   'Name'=>urlencode('php generate  json  Chinese '), 
   'Age'=>20 
  ); 
 
echo JSON($array);
echo '</br>';
echo urlencode('php generate  json  Chinese ');
 
?> 
</body>
</html>

Related articles: