Using annotations to control the automatic conversion from XML to JSON.
The basics
Example 1
Attributes become JSON properties. Elements become JSON properties with an object as value.
|
JSON:
|
Example 2
Elements having no attributes and just one text child, become simple JSON properties (not objects).
|
JSON:
|
Changing property names
Normally the name of a JSON property is identical to the XML element’s or attribute’s name. However you can use the annotation censhare:_annotation.property_name
to enforce a different name.
|
JSON:
|
Arrays
Multiple elements
Multiple sibling elements with same name become a JSON array.
|
JSON:
|
You can always force an array by using the annotation censhare:_annotation.multi
. This also works for single elements, which otherwise would not become an array, but an object property.
|
JSON:
|
Array grouping elements
Often it’s more convenient to group array elements by parent node, which must be tagged with the annotation censhare:_annotation.arraygroup
.
|
JSON:
|
If you omit the annotation the result will look different, since the parent node “elements” becomes a JSON object property, not an array. The name of the array property is then taken from the children elements, “e” in this example.
|
JSON:
|
Multidimensional arrays
Multidimensional arrays (e.g. a matrix) can be created by nesting elements tagged with the annotation censhare:_annotation.arraygroup
.
|
JSON:
|
Data types
JSON supports additional data types besides strings: number, boolean and null. To get property values in the correct data type in the JSON document, use the annotation censhare:_annotation.datatype
on text elements to convert the node’s value into the target data type.
|
JSON:
|
Note: If you create your XML attributes programmatically using the AXml/CXml Java objects or by an XSLT transformation using
xsl:attribute
, the type information is correctly stored in the DOM tree and will be used for a subsequent JSON serialization. This means that data type annotations can be omitted in such situations. Just make sure to write the attribute values by using the dedicated Java/XSL types (not as strings). This only works for attribute values and not for text nodes.