I need to produce json Output with numbers and string, both in double quotes in my REST API call.
Example:
[
{
"LastName":"abc",
"FirstName":"xyz",
"Id":"123",
},
{
"LastName":"mno",
"FirstName":"pqr",
"Id":"456",
}
]
As you can see the above output is what I require.
However the numbers 123 and 456 appear without double quotes as they are numbers. Does anyone know a workaround?
I am using org.json.JSONObject. My application first produces an XML which is then converted to JSON using the following lines of code:
JSONObject json = XML.toJSONObject(xml);
String jsonString = json.toString(PRINT_INDENT_FACTOR);
The jsonString above is directly rendered on browser in the REST API call. The numbers appear without double quotes. Is there any property under the JSONObject library which can solve this issue?
Thanks in advance!
====================== EDIT 1 ===================
I tried the following code based on the suggestions and the link provide in the comments by changing the library to use GSon 2.2.2 jar instead of JSONObject
GsonBuilder gb = new GsonBuilder();
gb.setPrettyPrinting();
gb.disableHtmlEscaping();
gb.setLongSerializationPolicy( LongSerializationPolicy.STRING );
Gson gson = gb.create();
File fXmlFile = new File("\\path\\test.xml");
String str = FileUtils.readFileToString(fXmlFile);
System.out.println(gson.toJson(str));
However the output still is with numbers without double quotes!!!! :(
what am i doing wrong?
====================== EDIT 2 ===================
Ok, LongSerializationPolicy.STRING works only for long type and not decimal\float. So the long values show up in double quotes. Then what about int , float and decimals. Those are numerical values too. How can I show them in double quotes?
====================== EDIT 3 ===================
Changed my libraries to jackson one and used the jackson-dataformat-xml-2.9.2.jar to get the JSON. So the numbers appear in double quotes now. Decimals, floats, ints etc. However the entire XML is not parsed. Only a section of the tags is parsed. its missing many other tags. I have read another post here that it is known to have limitations.
====================== EDIT 4 ===================
I have just done a string replace all using regex. That works.
jsonString = jsonString.replaceAll(":\s([\d]+)", ": \"$1\"");