Task 2: Specifying JSON Bindings

Example 16-4 shows a basic JSON binding that does not require compile time dependencies in addition to those required for normal JAXB usage. This example shows how to unmarshal JSON from a StreamSource into the user object SearchResults, add a new Result to the collection, and then marshal the new collection to System.out.

Task 4: Supporting Attributes

JSON does not use attributes; anything mapped with a @XmlAttribute annotation will be marshalled as an element. By default, EclipseLink triggers both the attribute and element events, thereby allowing either the mapped attribute or element to handle the value.

You can override this behavior by using the JSON_ATTRIBUTE_PREFIX property to specify an attribute prefix, as shown in Example 16-8. EclipseLink prepends the prefix to the attribute name during marshal and will recognize it during unmarshal.

In the example below the number field is mapped as an attribute with the prefix @.

You can also set the JSON_ATTRIBUTE_PREFIX property in the Map used when creating the JAXBContext, as shown in Example 16-9. All marshallers and unmarshallers created from the context will use the specified prefix.

Task 5: Supporting no Root Element

EclipseLink supports JSON documents without a root element. By default, if no @XmlRootElement annotation exists, the marshalled JSON document will not have a root element. You can override this behavior (that is omit the root element from the JSON output, even if the @XmlRootElementis specified) by setting the JSON_INCLUDE_ROOT property when marshalling a document, as shown in Example 16-10.

If the document has no root element, you must specify the class to unmarshal to.

Task 5 Using Namespaces

Because JSON does not use namespaces, by default all namespaces and prefixes are ignored when marshalling and unmarshalling. In some cases, this may be an issue if you have multiple mappings with the same local name – there will be no way to distinguish between the mappings.

With EclipseLink, you can supply a Map of namespace-to-prefix (or an instance of NamespacePrefixMapper) to the Marshaller and Unmarshaller. The namespace prefix will appear in the marshalled document prepended to the element name. EclipseLink will recognize the prefix during an unmarshal operation and the resulting Java objects will be placed in the proper namespaces.

The MarshallerProperties.NAMESPACE_PREFIX_MAPPER applies to both XML and JSON; UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER is a JSON-only property. XML unmarshalling can obtain the namespace information directly from the document.

When JSON is marshalled, the namespaces will be given the prefix from the Map separated by a dot ( . ):

{
"ns1.employee : {
"ns2.id" : 123
}
}

The dot separator can be set to any custom character by using the JSON_NAMESPACE_SEPARATOR property. Here, a colon ( : ) will be used instead: