Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preceding 0 gets removed while converting XML String to JSON Object [duplicate]

Tags:

java

json

xml

I am facing a strange issue while converting an XML string into JSON object in Java. I am using org.json.jar for to construct the JSON object but if one of the xml tag contains number, starting with 0, that number is appearing wrong in the JSON object.

Could anyone please help me to sort this out please? Please find below the method I am using to convert the XML string to JSON and also I have provided the input and output.

Method :

public static String toJSON(String xml) {
    String json = null;
    try {
        JSONObject jobj = XML.toJSONObject((String)xml);
        json = jobj.toString();

    }catch (JSONException e) {
        System.out.println("Json Exception " + (Object)e);
    }
    return json;
}

Input :

<box>0X</box> <number>012345</number>

Output : After converting to Json : {"number":"5349","box":"0X"}

In XML I have given number as 012345 but in JSON it is appearing as 5349! I am expecting 012345 in JSON as well.

Any help on this will be really helpful. Thank you in advance.

like image 645
user6626361 Avatar asked Feb 12 '26 11:02

user6626361


1 Answers

See similar question. The problem is in the implementation of stringToValue method in org.json.XML.

To disable automatic conversion to int/long which will strip out the leading zero, you can put the string value in CDATA and then it will work. e.g. the input could be:

<box>0X</box><number><![CDATA[012345]]></number>

like image 139
vsnyc Avatar answered Feb 14 '26 16:02

vsnyc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!