How to convert XML to JSON in Java and avoid the parser trying to parse strings into numbers
I'm using org json. XML library to parse XML into JSON http://www.json.org/javadoc/org/json/XML.html
In my XML document, there is a randomly generated ID field using [0-9] [A-Z] It should be a string Everything is normal until this unfortunate ID 123456789e1234 happens to be a digital scientific count This is a test code:
public class XmlToJsonTest { public static String testXML = "<MyXML><ID>123456789e1234</ID></MyXML>"; @Test public void testXMLtoJSON() throws JSONException { JSONObject testJsonObject = XML.toJSONObject(testXML); } }
This is the exception:
org.json.JSONException: JSON does not allow non-finite numbers.
The XML lib tojson () method first attempts to convert a string to integer, long or double. If not, it will give up parsing it into a number and treat it as a string In this case, string 123456789e1234 resolves to double Later, when lib passed double Isinfinite() throws jsonexception when it checks whether double is infinite, because 123456789e1234 is obviously larger than the finite standard of double
How do I force it not to parse values into numbers? In this case, is there a Java library that correctly converts XML to JSON?
Solution
Try this
import org.json.me.JSONObject; import cjm.component.cb.json.ToJSON; public class DummyClass { public static void main(String[] args) { try { String xml = "<MyXML><ID>123456789e1234</ID></MyXML>"; JSONObject obj = (new ToJSON().convertToJSON(xml)); System.out.println(obj); } catch (Exception e) { e.printStackTrace(); } } }
yield
-------- XML Detected -------- -------- JSON created Successfully -------- {"MyXML":{"ID":"123456789e1234"}}
Get conversion box