I have a class, written in Java, that makes a call to a PHP server for information on a series of items. This series should be returned in some sort of collection, such as in an array, a JSON encoded array, etc...
Is there a way that I could have PHP return the collection of data in some way that it could be easily parsed in Java and utilized as either an array or object? For example, if I JSON encode or serialize my PHP array, can it be easily JSON decoded or unserialized and then used as an array?
2 Answers 2
if your problem is because of the complicated class java has for actually parsing JSON, you may use JSON.simple library.
Here's a snippet of how to decode JSON (taken from the wiki page):
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=JSONValue.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2=(JSONObject)array.get(1);
System.out.println("======field \"1\"==========");
System.out.println(obj2.get("1"));
Comments
Yes and no. PHP has the function http://php.net/manual/en/function.json-encode.php to encode arrays in json.
The bigest Proble is that Java is a typed language and PHP is not.
You have to make sure that the values in your PHP array have the correct type or you ay get unexpected results.
Unset values are the most dangerous thing. If your PHP array contains null or false and your Java class expects an empty string you might run into trouble.
json_encode()andjson_decode()are native functions in PHP.