Reputation: 41
We are using jettison-1.3.3 for converting JaxB to Json.
We are facing an issue. whenever I have a String property that contains all numbers (i.e. String phone="12345";), the JSON response will display it as a number (12345) without having the double quotes.
If the value is coming as 1234AS in this case returns with double quote. How to fix this and making sure its always has double quotes.
Please help
Upvotes: 4
Views: 4127
Reputation: 368
There are type converters in the jettison. By default it uses default type converter. Default type convert removes double quotes if the value is numeric type.
To get always double quotes use SimpleConverter.
Create a system property - i.e System.setProperty("jettison.mapped.typeconverter.class", "org.codehaus.jettison.mapped.SimpleConverter");
So jettison uses simple converter and output values as string.
Upvotes: 3
Reputation: 149037
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
You could use the JSON-binding offered by MOXy for this use case.
Domain Model (Root)
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
int number;
String string;
}
Specifying MOXy as your JSON-Binding Provider
In a RESTful environment you can specify MOXyJsonProvider
as the MessageBodyReader
/MessageBodyWriter
for your JAX-RS application
In the standalone example below you can specify a jaxb.properties
file in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo Code
Below is a standalone example you can run to prove that everything works:
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Root root = new Root();
root.number = 1234;
root.string = "1234";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
Below is the output from running the demo code:
{
"number" : 1234,
"string" : "1234"
}
Upvotes: 2
Reputation: 68715
This seems to be an implicit "feature" of Jettison; it tries to introspect the actual data and figure out what's the best type fit. Better try using some other libraries such as Jackson. Jackson does not try to provide some unnecessary help causing such issues.
Upvotes: 1