javajsonxmljacksonformat-conversion

Convert JSON to XML in Java with different JSON object names


I have this JSON string:

{
    "purpose": {
        "caption": "Purpose",
        "value": "Buy a goat"
    },
    "goatValue": {
        "caption": "Goat value",
        "value": "4500000"
    },
    "loanAmount": {
        "caption": "Loan amount",
        "value": "5000000"
    },
    "childrenInfo": [{
        "gender": {
            "caption": "Gender",
            "value": "Boy"
        },
        "provider": {
            "caption": "Provider",
            "value": "Yes"
        },
        "age": {
            "caption": "Age",
            "value": "5"
        }
    },
    {
        "gender": {
            "caption": "Gender",
            "value": "Girl"
        },
        "provider": {
            "caption": "Provider",
            "value": "No"
        },
        "age": {
            "caption": "Age",
            "value": "17"
        }
    }]
}

And I want to convert it to this xml structure:

<Row>
    <caption>Purpose</caption>
    <value>Buy a goat</value>
</Row>
<Row>
    <caption>Goat value</caption>
    <value>4500000</value>
</Row>
<Row>
    <caption>Loan amount</caption>
    <value>5000000</value>
</Row>
<Row>
    <caption>Gender</caption>
    <value>Boy</value>
</Row>
<Row>
    <caption>Provider</caption>
    <value>Yes</value>
</Row>
<Row>
    <caption>Age</caption>
    <value>5</value>
</Row>
<Row>
    <caption>Gender</caption>
    <value>Girl</value>
</Row>
<Row>
    <caption>Provider</caption>
    <value>No</value>
</Row>
<Row>
    <caption>Age</caption>
    <value>17</value>
</Row>

This is suppose to work with any JSON object name (in this case purpose, goatValue and loanAmount) because there is no way to know the names of the JSON objects. I've tried using Jackson ObjectMapper and mapped the JSON string to

HashMap<String, HashMap<String, String>>

, but now I don't know what to do.

Any suggestions?


Solution

  • You need to read the JSON as a Map<String, Object> and create a Row object consisting of a caption and value field. After that you need to iterate over the entries in the map distinguishing between maps and lists of maps. In the case of maps, these need to be converted to Row objects and added to a collection of row objects. In the case of the lists of maps, the same thing needs to be done in an inner loop. When the iteration is done, the rows need to be added to a wrapper object which can then be converted to xml using an XmlMapper.

    I've created a gist that works on your example: https://gist.github.com/santmatthew/8f85399ad86fb45fec0be0c5df1a9825