TheStiff
TheStiff

Reputation: 395

Returning a dynamic Json in a Rest Service

I'm trying my hand on implementing a simple Restful Web Service using Spring Boot.

Currently, I want to parse an XML file to a Json object and return it as the response message. However I'm currently having problems defining the structure of the returned JSON object since it can vary depending on the XML file that I'm parsing.

This is a parsed XML-to-Json example of what I'm trying to return.

{
    "App": {
        "CR": {
            "Product": {
                "PRequest": {
                    "MF": "dfl3",
                    "Pri": "0",
                    "PC": "age",
                    "PCode": "Hca"
                }
            }
        },
        "SD": {
            "SDF": {
                "PRP": {
                    "_cCao": "str1234",
                    "_cSao": "str1234",
                    "_dao": "2012-12-13",
                    "_dCao": "2012-12-13",
                    "_dr": "2012-12-13",
                    "_nIDta": "str1234",
                    "_no": "1234"
                }
            }
        }
    }
}

Is there a way to return a dynamic Json object whose structure is only defined at run time?

Upvotes: 0

Views: 1201

Answers (1)

T67
T67

Reputation: 61

You can accomplish this very easily with org.json:

String xmlString = "<note><to>Bill</to><from>Ben</from><body>Hello!</body></note>";
JSONObject jsonObject = XML.toJSONObject(xmlString);
String jsonString = jsonObject.toString();

// Evaluates to:
// {"note":{"from":"Ben","to":"Bill","body":"Hello!"}}

This will turn an XML string into a JSONObject which you can then manipulate or turn into a JSON string.

If you're using Maven, you can add a dependency for org.json by adding this to your pom.xml:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

Upvotes: 2

Related Questions