I'm trying to do a simple test for eclipselink's JSON to JAXB object capabilities. I originally planned on using moxy to generate json, and then again using it to marshal out to objects, however attempting to set the eclipselink.media-type and the eclipselink.json.include-root properties both are throwing a PropertyException. I'm sure it's because I've set something up wrong.
here is my main method: (i have a package moxyTest, with a single Foo class that has two string values)
JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory
.createContext(new Class[] { moxyTest.Foo.class }, null);
Marshaller marsh = jc.createMarshaller();
Foo firstObject = new Foo("value1", "value2");
marsh.setProperty("eclipselink.media-type", "application/json");
marsh.marshal(firstObject, System.out);
I didn't bother with a jaxb.properties file since i'm specifying the eclipselink one explicitly, but I also tried adding one and it didn't do anything. The curious thing is that it's not throwing a propertyNotFoundException, but rather just a plain PropertyException.
with that being said, on a side note, I know moxy has object->xml and object-> json, is there a fast way to directly json->xml or vice versa?
As long as you are using EclipseLink 2.4.0 or newer your code will work as is:
Domain Model (Foo)
package moxyTest;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
private String a;
private String b;
public Foo() {
}
public Foo(String a, String b) {
this.a = a;
this.b = b;
}
}
Demo
package moxyTest;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory
.createContext(new Class[] { moxyTest.Foo.class }, null);
Marshaller marsh = jc.createMarshaller();
Foo firstObject = new Foo("value1", "value2");
marsh.setProperty("eclipselink.media-type", "application/json");
marsh.marshal(firstObject, System.out);
}
}
Output
{"foo":{"a":"value1","b":"value2"}}