Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A lot depends on how you choose to represent models in your code.</p> <p>Let's assume you use records. Here's a contrived example of how you might "annotate" a record and provide serializers for XML and JSON.</p> <pre><code>;; Depends on cheshire and data.xml (ns user (:require [cheshire.core :as json] [clojure.data.xml :as xml])) (defrecord Person [name age hometown]) (defrecord Animal [name sound]) (def xml-attrs {Person [:name :age] Animal [:name]}) (defn record-&gt;xml-data [rec] (let [tag (-&gt; rec class .getSimpleName .toLowerCase keyword) attrs (select-keys rec (xml-attrs (class rec))) content (for [[k v] rec :when (not (contains? attrs k))] (xml/element k nil (str v)))] (apply xml/element tag attrs content))) (defn record-&gt;xml [rec] (xml/emit-str (record-&gt;xml-data rec))) (defn record-&gt;json [rec] (json/generate-string rec)) </code></pre> <p>Usage:</p> <pre><code>&gt; (def bob (Person. "Bob" 24 "New York")) #'user/bob &gt; (println (record-&gt;xml bob)) &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;person age="24" name="Bob"&gt;&lt;hometown&gt;New York&lt;/hometown&gt;&lt;/person&gt; nil &gt; (println (record-&gt;json bob)) {"name":"Bob","age":24,"hometown":"New York"} nil &gt; (println (record-&gt;xml (Animal. "Fido" "Bark!"))) &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;animal name="Fido"&gt;&lt;sound&gt;Bark!&lt;/sound&gt;&lt;/animal&gt; nil </code></pre> <p>A macro could be created to define a record and its XML attributes in a singe statement. E.g.,</p> <pre><code>(defrecord-xml Person [^:xml-attr name ^:xml-attr age hometown]) </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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