Paul Hammant's Blog: Using XStream to forward JSON to a browser
Patching XStream for JSON compatibilityhttp://jira.codehaus.org/browse/XSTR-321 is a patch for XStream to allow serialization to JSON. The theory is that your AJAX browser logic dispatches a classic REST GET request like http://weather.com/give-me-termperature-for?city=chicago and the reply is in JSON.
XStream exs = new XStream(new JsonHierarchicalStreamDriver());The method toXML is of course malnamed. But seeing as Joe and the gang are writing binary serialization presently, there could be a rename for XStream to toSerializedForm (or better). Speaking of better Joe normally redoes my stuff.
String json = xs.toXML(objToSerialize)
The JSON serializer does booleans and ints without quotes that would imply strings. It also omits braces where there are no child elements - the object your serializing in many cases will be a lot simpler that the 'arbitrary object tree' that XStream supports. Arrays, lists and sets are handled by the JSON serializer, but don't use XStream.addImplicitCollection(..) as it will nobble the array handling functionality.
See JsonHierarchicalStreamDriverTest.java in the zip attached the the Jira issue for some more complex examples of usage.
So for a limited time only Paul's version of XStream is available here for experimental purposes only. Seems apt to call it pstream.
blog comments powered by Disqus
June 14th, 2006