|
|
|
Re: MOXy: <xml-attribute> and JSON [message #789911 is a reply to message #789883] |
Fri, 03 February 2012 15:08 |
|
It turns out that only the "read-only" attributes are not be written out with JSON. Again, is this expected behavior?
This is expected behaviour. If you specify a mapping as "read-only" then it will not be marshalled to XML or JSON.
<xml-attribute java-attribute="foo" read-only="true"/>
Below is complete example demonstrating an object mapping with MOXy's external mapping document with an attribute property marshalled to both XML and JSON:
feb3.Root
The following will be used as the domain model:
package feb3;
public class Root {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
feb3/oxm.xml
We will use MOXy's external mapping document to map the foo property as an XML attribute.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="feb3">
<java-types>
<java-type name="Root">
<xml-root-element name="rss"/>
<java-attributes>
<xml-attribute java-attribute="foo"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
feb3.Demo
The following code demonstrates how to bootstrap from MOXy's external mapping document, and how to marshal to both XML (default) and JSON.
package feb3;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "feb3/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Root root = new Root();
root.setFoo("Hello World");
// Marshal to XML
marshaller.marshal(root, System.out);
// Marshal to JSON
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.marshal(root, System.out);
}
}
Output
Here is the XML and JSON output from running the demo code:
<?xml version="1.0" encoding="UTF-8"?>
<rss foo="Hello World"/>
{"rss" :
{"foo" : "Hello World"}}
|
|
|
|
Powered by
FUDForum. Page generated in 0.03711 seconds