I am converting simple XML to JSON using org.json
lib:
import org.json.JSONObject;
import org.json.XML;
public class TestJson {
public static void test_number() {
String xml = "<BALANCE>32032033.10</BALANCE>";
JSONObject jsonObj = XML.toJSONObject(xml);
String json_str = jsonObj.toString(4);
System.out.println(String.format("%s\n----\n%s", xml, json_str));
}
public static void main(String[] args) {
try {
test_number();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My results:
<BALANCE>32032033.10</BALANCE>
----
{"BALANCE": 3.20320331E7}
As you see the format of number changed from normal, to scientific. How can I preserve number format? I would like to see JSON as:
{"BALANCE": 32032033.10}
or preferable as string:
{"BALANCE": "32032033.10"}
I use org.json
from json-20190722.jar
Hope the below code will help to resolve the issue. Please use XML.toJSONObject(xml,true)
instead of XML.toJSONObject(xml);
import org.json.JSONObject;
import org.json.XML;
public class TestJson {
public static void test_number() {
String xml = "<BALANCE>32032033.10</BALANCE>";
JSONObject jsonObj = XML.toJSONObject(xml,true);
System.out.println(String.format("%s\n----\n%s", xml, jsonObj.toString()));
}
public static void main(String[] args) {
try {
test_number();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
<BALANCE>32032033.10</BALANCE>
----
{"BALANCE":"32032033.10"}