I have a Java class annotated with @XmlRootElement. This Java class has a long property (private long id) that I want to return to a JavaScript-client.
I create the JSON as follows:
MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120);
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
Class[] types = {MyEntity.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
json = writer.toString();
System.out.println(writer.toString());
This will be generated:
{"name":"Benny Neugebauer","id":2517564202727464120}
But the problem is that the long value is too large for the JavaScript client. Therefore, I would like to return this value as a string (without making the long a string in Java).
Is there an annotation (or something similar) that can generate the following?
{"name":"Benny Neugebauer","id":"2517564202727464120"}
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
longproperty with@XmlSchemaType(name="string")to indicate that it should be marshalled as aString.jaxb.properties
To configure MOXy as your JAXB provider you need to include a file called
jaxb.propertiesin the same package as your domain model (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).Demo
I have modified your sample code to show what it would look like if you used MOXy.
Output
Below is the output from running the demo code:
For More Information