Say I have a REST API in java and it supports responses that are JSON or XML. The answers contain the same data, but the form is not identical. For example, in json, I could:
{ "persons": [ { "name":"Bob", "age":24, "hometown":"New York" } ] }
While in XML it looks like this:
<persons> <person name="bob" age="24"> <hometown>New York</hometown> </person> </persons>
That is, some values ββare attributes for a person, while others are child attributes. In Java, using JAXB and Jackson, it's easy to hide such differences with annotations on model objects, for example:
public class Person { @XmlAttribute String name; @XmlAttribute Integer age; @XmlElement String hometown; }
JAXB reads annotations, and Jackson uses field names to figure out what to do. Thus, with one model it is easy to support several output formats.
So my question is: how to do the same in clojure. I know that there is clj-json that can easily convert clojure maps and vectors to json (using jackson if I'm not mistaken). And I know that there are both clojure.xml.emit and clojure.contrib.xml.prxml that can deserialize maps and vectors into XML. But if Iβm not mistaken, I donβt think that these two will work together very well.
Because prxml expects xml nodes to be expressed as vectors, and xml attributes will be expressed as a map, fundamentally different from clj-json, where vectors are arrays and maps represent objects. And clojure.core.emit expects a map of the form {:tag :person :attrs {:name "Bob" :age 24} :content ...}
, which is completely different from what clj-json wants.
The only thing I can think of is to format the data structures for prxml in my code, and then write a function that converts the data structure to what clj-json wants when the response type is JSON. But it looks like the lame. I would prefer if there were a couple of JSON and XML libraries that were compatible with both JAXB and Jackson.
Ideas?