David Pollak was right about XML and JSON

David Pollak was right about XML and JSON, but perhaps in a different way. XML cannot be converted to (clean) JSON.

Suppose we have a shopping cart in XML which we want to convert to JSON:

One representation in JSON would be (cart could be omitted):

We convert a list of nodes with the same name to a JSON array, xml2json-xslt does this for example. What happens if we only have one item in our shopping cart?

Then our converter cannot detect that items is a list and will convert the XML to:

which is semantically something completely different. And very unpleasent for the receiver of our JSON code, because sometimes he gets an array and sometimes an object.

One way to solve the problem is to annotate the XML (looks ugly but works):

and adding an additional condition to the XSLT

or namespacing (doesn’t work yet, we get lots of namespaces and misuse XML namespaces) ?

So David was right, I’m not sure he new why ;-)

Thanks for listening.

David Pollak (from Lift): “There’s no way to convert from XML to JSON because XML contains sequences not expressible in JSON”

Hmm[*]. Not sure if this is true (with CDATA, #Text and @attributes handled in some converters). For me the problem is more that there are too many ways to convert XML to JSON. For exampe the Badgerfish convention. Or the the Google and Yahoo versions. Or the XML.com way. And the Parker convention.

But the ways in Javascript to convert XML to JSON are either slow, very basic, use XSLT, use nasty Regex or cannot create simple JSON which feels JSON like.

* Note to self: Should start using Twitter for this [**].
** Did start Twitter

Update: Any ideas for a good XML to JSON conversion which feels JSON like (no need to be bidirectional)?

Update 2: I currently use XSLT with nice results, Safari doesn’t work yet and neither does Chrome. More to come.

scala.xml.Node, text/xml and Jersey: How to do REST with Scala

Scala has native support for xml in the language via scala.xml.Node

There is an excellent book called scala.xml on XML and Scala so this post won’t go into more detail.

Using the XML support in Scala makes it easy to write REST applications with Jersey. I’ve shown how to create JSON with a JsonBuilder in Scala before.

We need a Resource to handle our REST requests. As a response to a GET request on /helloWorld/xml we create a Scala XML node:

Jersey needs to know how to translate an object of scala.xml.Node to a HTTP response. This is usually done by implementing a MessageBodyWriter that maps an object and a mime type – scala.xml.Node and text/xml in this case – to a response.

Voila, we now get <message>Hello world</message> when calling /helloWorld/xml.

Thanks for listening.