As we all know, using json_encode can easily and quickly encode an object in json format. However, if the object's attributes contain Chinese characters, the problem arises. Json_encode converts Chinese to unicode encoding. for example, after 'encoding' is processed by json_encode, it is changed to '\ u80e5'. in the final json, the Chinese part is replaced with unicode encoding. What we need to solve is to convert the object to json and ensure that the Chinese character inside the object still appears in json as normal Chinese. now it seems that json_encode alone cannot achieve the goal.
My solution: perform url encoding for the Chinese fields in the class first, then perform json encoding (jsonencode) for the object, and finally url decoding (urldecode) json, that is, the final json. the Chinese in it is still the Chinese!
The test code is as follows:
The code is as follows:
Class myClass {
Public $ item1 = 1;
Public $ item2 = 'Chinese ';
Function to_json (){
// Url encoding to avoid converting Chinese to unicode using json_encode
$ This-> item2 = urlencode ($ this-> item2 );
$ Str_json = json_encode ($ this );
// Url decoding. after converting json, all attributes are returned, so that the object attributes remain unchanged.
$ This-> item2 = urldecode ($ this-> item2 );
Return urldecode ($ str_json );
}
}
$ C = new myClass ();
Echo json_encode ($ c );
Echo'
';
Echo $ c-> to_json ();
Echo'
';
Echo json_encode ($ c );
Echo'
';
Echo json_encode ('authorization ');
?>
Program output result:
The code is as follows:
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
{"Item1": 1, "item2": "Chinese "}
{"Item1": 1, "item2": "\ u4e2d \ u6587 "}
"\ U80e5"
I hope this article will serve as a reference to collect better solutions ......!