How to return a long property as JSON string value with JAXB
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is how you could accomplish this use case with MOXy as your JSON provider.
MyEntity
You would annotate your long
property with @XmlSchemaType(name="string")
to indicate that it should be marshalled as a String
.
package forum11737597;import javax.xml.bind.annotation.*;@XmlRootElementpublic class MyEntity { private String name; private long id; public MyEntity() { } public MyEntity(String name, long id) { setName(name); setId(id); } public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlSchemaType(name="string") public long getId() { return id; } public void setId(long id) { this.id = id; }}
jaxb.properties
To configure MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
I have modified your sample code to show what it would look like if you used MOXy.
package forum11737597;import java.io.StringWriter;import java.util.*;import javax.xml.bind.*;import org.eclipse.persistence.jaxb.JAXBContextProperties;public class Demo { public static void main(String[] args) throws Exception { MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120L); StringWriter writer = new StringWriter(); Map<String, Object> config = new HashMap<String, Object>(2); config.put(JAXBContextProperties.MEDIA_TYPE, "application/json"); config.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false); Class[] types = {MyEntity.class}; JAXBContext context = JAXBContext.newInstance(types, config); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(myInstance, writer); System.out.println(writer.toString()); }}
Output
Below is the output from running the demo code:
{"id":"2517564202727464120","name":"Benny Neugebauer"}
For More Information