PHP communicate with Java using JSON – Unicode Version
JSON is one of the most popular message exchange format nowadays used in web application.Most of the time,we used JSON as a communication message format between Javascript and Server side language,such as PHP.We can also use it to exchange messages between different languages.
For instance,we want to store a PHP array in database and later to be processed by Java,we can do something like
$aValue = array("key1"=>"value1","key2"=>"value2");
$sEncodedValue = json_encode($aValue)
//we will get something like {"key1":"value1","key2":"value2"}
//and then, we store the value to db
On the other hand,we use Java to read it and decode it.
//read from db and got the resultset,assuming we are using JDBC
while (rs.next()){
String rawValue = rs.getString("encodedValue");
// since we encoded an associative array,it will be translated to a Java Map object instance.
// we are using JSON-lib for JSON parsing the following example
JSONObject json = JSONObject.fromObject(jsonString);
Map decodedValue = (Map) JSONObject.toBean(json, Map.class);
String value1 = decodedValue.get("key1");
}
What if we are trying to store unicode value using JSON format in PHP?
For example,
$aValue = array("key1"=>"你好吗","key2"=>"value2");
$sEncodedValue = json_encode($aValue);
//This is what we get after encoded
//{"key1":"\u4f60\u597d\u5417","key2":"value2"}
If you decoded it back to Java,key1 value will return “u4f60u597du5417″ instead.This is so wrong.
How to solve it?
We can use mb_convert_encoding function in PHP.
Let’s make some changes to our code.
$aValue = array("key1"=>mb_convert_encoding("你好吗", "UTF-8"),"key2"=>"value2");
$sEncodedValue = json_encode($aValue);
By doing so,values are stored in database in unicode format,and you can decode it back in Java.
Happy coding.
Hello from Russia!
Can I quote a post in your blog with the link to you?
sure…