In Android development, encoding problems occurred when connecting with the server-side interface. The data obtained from the server is "/u8bbe/u59071ID-/u8bbe/u59071/u540d/u79f0;/u8bbe/u59073id-/u8bbe/u59073/u540d/u79f0;/u8bbe/u59077id-/u8bbe/u59077/u540d/u79f0" The interface is returned after encoding and then encoding through json_encode in the php function. It does not work on the client's decoding through java.net.URLdecoder.decode(), but it can be decoded normally by copying the above string into the decode() method. The received string is encoded by utf-8 and does not work. Finally, searching for relevant information online to find a solution.
1. json_encode function:
json_encode – JSON encoding of variables.
Description: string json_encode ($value), returns the JSON form of the value value.
Parameters: The value to be encoded can be any data type except for the resource type
This function can only accept UTF-8 encoded data (translation note: refers to data of character/string type)
Return value: If the encoding is successful, a string represented in JSON will be returned.
2. The client decodes in Java:
The first method
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(); }Just use the unescapeUnicode() method to decode it directly.
2. Use json_simple.jar package to parse
Download address: //www.VeVB.COM/softs/455885.html
JSON.simple is a simple Java class library for parsing and generating JSON text. It does not depend on other libraries and has high performance.
Object obj=JSONValue.parse(jsonStr);return obj.toString();
PHP server-side solution:
<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 generates json Chinese'), 'Age'=>20 ); echo JSON($array); echo '</br>';echo urlencode('php generates json Chinese'); ?> </body></html>