Dilip B S
Dilip B S

Reputation: 203

XML to json conversion, in Java, while preserving the data types

I am using org.json api to convert xml to json. The problem is certain tags in my xml contain non string values (i.e., int, boolean, double etc...).

The code I am using below, is successfully converting xml to json, but the primitive data types are converted to string in the json response. For eg: <age>10<age> in xml gets converted to {"age" : "10" } in which the value 10 in json is a String which should be an Integer. For example {"age" : 10 }.

The xml input which I give for conversion, is dynamic and will change frequently. But for the sake of showing it as an example, I am saving the xml as a String. The dynamically generated xml code will be saved in a string variable.

Can anyone help me out in converting the xml to json, while preserving the data types? Below is the code

import org.json.*;
public class XmlToJson {
     private static String xmlCode = 
                     "<handler>
                         <price>10</price>
                         <item>rice</item>
                         <VALUE>3434</VALUE>
                     </handler>
                     <flow>
                     </flow>";
         public static void main(String[] args) throws JSONException{
               JSONObject xmlJsonObj=null;
               xmlJsonObj = XML.toJSONObject(xmlCode);
               System.out.println(xmlJsonObj.toString(1));
         }
}

Sample output:

{
    "flow": "",
    "handler": {
        "VALUE": "3434",
        "item": "rice",
        "price": "10"
    }
}

The expected behavior is:

{
    "flow": "",
    "handler": {
        "VALUE": 3434,
        "item": "rice",
        "price": 10
    }
}

Upvotes: 2

Views: 4202

Answers (3)

tomaj
tomaj

Reputation: 1590

You should have a look at my open source library unXml, which parses xml, and outputs Json. It's written for Java 8, and uses the (awesome) Jackson Json-library.

UnXml is available on Maven Central.

Given this xml (Added a root to make wellformed)

<root>
    <handler>
        <price>10</price>
        <item>rice</item>
        <VALUE>3434</VALUE>
    </handler>
    <flow></flow>
</root>

You create a parser like this

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.Parsing;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;

public class XmlParser {
    public ObjectNode parseXml(String inputXml){
        Parsing parsing = ParsingFactory.getInstance().create();
        Document document = parsing.xml().document(inputXml);

        Parser<ObjectNode> parser = parsing.obj("root")
            .attribute("flow")
            .attribute("handler",  "handler", parsing.obj()
                .attribute("price", "price", parsing.number())
                .attribute("item")
                .attribute("value", "VALUE", parsing.with(Integer::parseInt))
            )
            .build();

        ObjectNode result = parser.apply(document);
        return result;
    }
}

Which will return this Json

{
    "handler":{
        "item":"rice",
        "price":10.0,
        "value":3434
    },
    "flow":""
}

Upvotes: 2

StaxMan
StaxMan

Reputation: 116472

I second Konstantin's suggestion of using POJOs in-between XML and JSON -- otherwise you will be having endless problems due to mismatch between the two. Specifically, XML has "native" way of expressing arrays/Lists, so handling of empty and single-element lists/arrays typically produces odd results.

My suggestion would be to use Jackson for JSON and either JAXB or Jackson XML-data-binding for XML -- that way you can also use JAXB annotations for extra information, if naming has to be changed or so.

And whatever else you use, dump org.json package; alternatives are better nowadays so that package serves mostly as historical relic (it was useful when alternatives weren't around).

Upvotes: 0

Konstantin Pribluda
Konstantin Pribluda

Reputation: 12367

If your schema is set, you can go through databinding with POJOs ( convert XML into JSOs, convert POJOs to JSON ) - there is a lot of databinding tools and I would recomment those working on top of pull-model ( XStream for XML, GSON for JSON - but there is a rich choice to pich your favorite )

If you are better on XML side, you can also write XSLT transformation which will convert XML to whatever you like , also JSON - though I personally find JavaBeans way easier

Upvotes: 2

Related Questions