xml to json conversion issue in java, 1st leading zero discarded fom string -


my xml contains attribute value "0123" want treat string, after conversion xml json per following code leading 0 gets discarded attribute value.

used classes

import org.jdom.attribute; import org.jdom.document; import org.jdom.output.format; import org.jdom.output.xmloutputter; import org.json.jsonobject; import org.json.xml; 

//covert xml json

    org.jdom.document jdomdocument = new document();     org.jdom.element attribute = new org.jdom.element("attribute");     jdomdocument.setrootelement(attribute);      org.jdom.element valueelement = new  org.jdom.element("value");     valueelement.settext(getvalue()); // "0123"    // getvalue() return boolean,string,long,date, time etc..       root.addcontent(valueelement);     string xmlval = new    xmloutputter(format.getprettyformat()).outputstring(jdomdocument);     jsonobject xmljsonobj = xml.tojsonobject(xmlval);     string jsonprettyprintstring = xmljsonobj.tostring(4); 

how resolve issue ?

looking @ code xml.java - in particular stringtovalue method

"try convert string number, boolean, or null".   

the code below - can see tries parse number first, in case trim leading zeros. test try adding non-numeric character in string - think preserve leading zeros.

it looks behaviour you're seeing baked library. not great, though docs function tojsonobject warn

"some information may lost in transformation because json data format , xml document format" 

teh codez :

// if might number, try converting it. if doesn't work, // return string.          try {             char initial = string.charat(0);             boolean negative = false;             if (initial == '-') {                 initial = string.charat(1);                 negative = true;             }             if (initial == '0' && string.charat(negative ? 2 : 1) == '0') {                 return string;             }             if ((initial >= '0' && initial <= '9')) {                 if (string.indexof('.') >= 0) {                     return double.valueof(string);                 } else if (string.indexof('e') < 0 && string.indexof('e') < 0) {                     long mylong = new long(string);                     if (mylong.longvalue() == mylong.intvalue()) {                         return new integer(mylong.intvalue());                     } else {                         return mylong;                     }                 }             }         } catch (exception ignore) {         } 

edit : looks bug in library. believe should use

(negative ? 1 : 0) 

because current behaviour wrongly interprets value single leading 0 being number. correctly recognizes 2 or more leading zeros being string, confirmed asker.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -