android開發中在和服務器端接口對接時出現編碼問題,從服務器端獲取到的數據是 "/u8bbe/u59071ID-/u8bbe/u59071/u540d/u79f0;/u8bbe/u59073id-/u8bbe/u59073/u540d/u79f0;/u8bbe/u59077id-/u8bbe/u59077/u540d/u79f0" 接口是通過php函數中json_encode進行編碼后返回的,在客戶端通過java.net.URLdecoder.decode()解碼不管用,但是直接將以上字符串復制到decode()方法中可以正常解碼,把接收到的字符串經過utf-8編碼后不管用,最后在網上搜索相關資料找到解決方法。
一,json_encode作用:
json_encode ― 對變量進行 JSON 編碼。
說明:string json_encode ($value ),返回 value 值的 JSON 形式。
參數:待編碼的 value ,除了resource 類型之外,可以為任何數據類型
該函數只能接受 UTF-8 編碼的數據(譯注:指字符/字符串類型的數據)
返回值:編碼成功則返回一個以 JSON 形式表示的 string 。
二,客戶端用java語言解碼:
第一種方法
public String unescapeUnicode(String str){ StringBuffer b=new StringBuffer(); Matcher m = Pattern.compile("http:////u([0-9a-fA-F]{4})").matcher(str); while(m.find()) b.append((char)Integer.parseInt(m.group(1),16)); return b.toString(); }直接使用unescapeUnicode()方法解碼就可以了。
2. 使用 json_simple.jar 包解析
下載地址://m.survivalescaperooms.com/softs/455885.html
JSON.simple是一個簡單的Java類庫,用于解析和生成JSON文本。不依賴于其它類庫,性能高。
Object obj=JSONValue.parse(jsonStr);return obj.toString();
PHP服務器端解決方法:
<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><title>php生成 json 中文</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生成 json 中文'), 'Age'=>20 ); echo JSON($array);echo '</br>';echo urlencode('php生成 json 中文'); ?> </body></html>新聞熱點
疑難解答