smart-fun / XmlToJson

Android Library for converting XML to JSON and JSON to XML
Apache License 2.0
558 stars 112 forks source link

wrong type and value while converting from xml to json #2

Closed lucarocchi closed 7 years ago

lucarocchi commented 7 years ago

hello , here is the problem : 1) my xml contains an attribute id="12345.320" 2) as i converted it to json and get the id back as string, it became "12345.32", that is the trailing 0 disappear

What's happened? The problems comes from the code below , in fact the id get converted as Double,and that was not supposed to be the case So,my opinion it would be better to simply set the value as string and let is as is Just want to notice you about that in the case you would fix it

Thank you for your good work Luca

private void putContent(JSONObject json, String tag, String content) .... try { Integer integer = Integer.parseInt(content); json.put(tag, integer); } catch (NumberFormatException exceptionInt) { try { Double number = Double.parseDouble(content); json.put(tag, number.doubleValue()); } catch (NumberFormatException exceptionDouble) { json.put(tag, content); } }

smart-fun commented 7 years ago

Hello Luca and thank you for your feedback.

It sounds logical to me that string numbers are converted to numbers, but I understand your need. I can propose to add some options like "force an attribute to be a String" or "force a content to be a String". With that kind of options the user will be able to choose between String or Double.

What do you think ?

Arnaud.

lucarocchi commented 7 years ago

I think that would be a good solution as well ! Luca

smart-fun commented 7 years ago

Hello Luca,

I have added a method in the Builder: forceStringForPath(String path). It works for both Attributes or Content. It can be used like this:

String json = new XmlToJson.Builder(xml)
        .forceStringForPath("/library/book/id")
        .build().toString();

I did a pre-release 1.2.1, could you please use it and tell me if all is ok for you, so that I can officially release it?

thanks!

Arnaud.

lucarocchi commented 7 years ago

Yes it works as expected, thank you Luca

screen shot 2017-04-03 at 11 36 52
smart-fun commented 7 years ago

Good news ! :)

I just released this new version and updated the documentation.

Thanks again for your feedback!

I'm now closing this ticket as the problem is solved.

Arnaud.