Using JSON for Java and PHP interop
I’ve been playing with Markov chains for doing ‘random’ text generation. Had an interesting problem in that I needed the GUI code to run on a PHP based web server but I didn’t want to have the processing of the source files occur every time. I also had a nice Java program doing all the source text processing for me and I didn’t really feel like porting it over to PHP either.
What I needed was to store the data generated by the Java app in a format that I could use in my PHP pages.
I initially was going to serialise the data into a binary file or into XML but to be honest this seemed like just to much work and I’m (like most coders) a bit lazy.
Enter JSON, the JavaScript Object Notation. This is a format like XML that supports the light-weight encoding of data, however it also supports types and in fact is executable in Javascript to convert a JSON string directly into Javascript objects and arrays. This makes it very useful for things like AJAX applications.
JSON has wide platform support so both PHP and Java can encode objects and arrays into JSON and visa-versa. Even better to do so is very easy which appeals to my lazy coder nature :)
For instance to write out a popluated Java HashMap to file using JSON-lib is as simple as:
Map map = new HashMap();<br />
map.put( "name", "json" );<br />
map.put( "bool", Boolean.TRUE );<br />
map.put( "int", new Integer(1) );<br />
map.put( "arr", new String[]{"a","b"} );<br />
JSONObject jsonObject = JSONObject.fromObject( map );<br />
System.out.println( jsonObject );<br />
// prints: {"arr":["a","b"],"int":1,"name":"json","bool":true}
On the PHP side of things, there is a built in function (under 5.2.0) called _phpdecode() which is used as follows:
<?php<br />
$jsonString = '{"arr":["a","b"],"int":1,"name":"json","bool":true}';<br />
$decoded=json_decode($jsonString,true);<br />
var_dump($decoded);<br />
// prints: array(4) { ["arr"]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } ["int"]=> int(1) ["name"]=> string(4) "json" ["bool"]=> bool(true) }<br />
?>
Nice and neat.
So my final solution is:
- Java application processes the source text files and builds up the appropriate maps and data for the Markov chains
- Using JSON-lib it generates strings for the data and saves them to files
- My PHP page loads the files, does a json_decode() to get the Markov chain data loaded
- The PHP then generates the text using the loaded Markov chain data
Just too easy :)