Jettison with json marshalling converting a string data type to an integer type when the value is numeric

We use jettison-1.3.3 to convert JaxB to Json.

We are facing a problem. whenever I have a String property that contains all numbers (ie String phone = "12345";), the JSON response displays it as a number (12345) without double quotes.

If the value comes as 1234AS, in this case it is returned with a double quote. How to fix this and make sure it always has double quotes.

Please, help

+4
source share
3 answers

There are type converters in the gateway. By default, the default type converter is used. The default type conversion removes double quotes if the value is numeric.

To always get double quotes, use SimpleConverter.

Create a system property - i.e. System.setProperty ("jettison.mapped.typeconverter.class", "org.codehaus.jettison.mapped.SimpleConverter");

Thus, jettison uses a simple converter and output values ​​as a string.

+3
source

Note. I am an EclipseLink JAXB (MOXy) and a member of the JAXB Group (JSR-222) .

You can 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 a JSON Binding Provider

In a RESTful environment, you can specify MOXyJsonProvider as MessageBodyReader / MessageBodyWriter for your JAX-RS application

In a separate example below, you can specify the 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

The following is a separate example that 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

The following is the result of running the demo code:

 { "number" : 1234, "string" : "1234" } 
+2
source

This seems to be an implicit "feature" of Jettison; he is trying to research the evidence and figure out which best type is right. Better try using some other libraries like Jackson. Jackson is not trying to provide some undue help by causing such problems.

+1
source

Source: https://habr.com/ru/post/1479895/


All Articles