How to convert XML to JSON in Java and avoid the parser to try to parse String as numbers

I am using the org.json.XML library to parse XML in JSON. http://www.json.org/javadoc/org/json/XML.html

My XML document has an ID field that is randomly generated using [0-9] [az]. It is intended for String. Everything works fine until this bad ID 123456789e1234 appears, which is the scientific note of the number. Here is a snippet of 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);
    }
}

Here's the exception:

org.json.JSONException: JSON does not allow non-finite numbers.

XML lib toJson() String Integer, Long Double, , String. String 123456789e1234 . , lib , double Double.isInfinite(), JSON, , , 123456789e1234 , .

? - java-, XML JSON ?

+4
2

...

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();
    }
}
}

 -------- XML Detected -------- 
 -------- JSON created Successfully -------- 
{"MyXML":{"ID":"123456789e1234"}}

Jar ....

0

, :

String testXML = "<MyXML><ID>123456789e1234</ID></MyXML>";
JSONObject testJsonObject = org.json.XML.toJSONObject(testXML);
System.out.println(testJsonObject.getJSONObject("MyXML").getString("ID"));
0

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


All Articles