Note that there are some explanatory texts on larger screens.

plurals
  1. POsupport both xml and json REST response in clojure
    primarykey
    data
    text
    <p>Say I have a REST API in java, and it supports responses that are either JSON or XML. The responses contain the same data, but the form is not identical. For example, in json I might have:</p> <pre><code>{ "persons": [ { "name":"Bob", "age":24, "hometown":"New York" } ] } </code></pre> <p>Whereas in XML it looks like this:</p> <pre><code>&lt;persons&gt; &lt;person name="bob" age="24"&gt; &lt;hometown&gt;New York&lt;/hometown&gt; &lt;/person&gt; &lt;/persons&gt; </code></pre> <p>Which is to say that some values are attributes on person, and others are child elements. In Java, using JAXB and Jackson, it's easy to hide such differences with annotations on the model objects, for example:</p> <pre><code>public class Person { @XmlAttribute String name; @XmlAttribute Integer age; @XmlElement String hometown; } </code></pre> <p>JAXB reads the annotations, and Jackson uses the field names to figure out what to do. So with a single model it's easy to support multiple output formats.</p> <p>So my question is, how to do the same thing in clojure. I know that there is clj-json which can easily convert clojure maps and vectors to json (using jackson if I'm not mistaken). And I know there is both clojure.xml.emit and clojure.contrib.xml.prxml that can deserialize maps &amp; vectors to XML. But unless I'm mistaken, I don't think these two would work together very well. </p> <p>Because prxml expects xml nodes to be expressed as vectors, and xml attributes to be expressed as a map, fundamentally different than the working of clj-json, where vectors represent arrays, and maps represent objects. And clojure.core.emit expects a map in the form <code>{:tag :person :attrs {:name "Bob" :age 24} :content ...}</code> which is again completely different than what clj-json wants.</p> <p>The only thing I can think of is to format the data structures for prxml in my code, and then write a function that transforms the data structure to what clj-json wants when the response type is JSON. But that seems kind of lame. I would prefer if there was a pair of JSON and XML libraries that were compatible in the way that JAXB and Jackson are.</p> <p>Ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload