Change conversion JSON array to XML when using org.json

53 views Asked by At

I'm converting a complex JSON object to XML and using the org.json framework. Unfortunately, JSON array's are not converted like expected. How do I change this?

Sample:

pom.xml

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
    </dependency>
</dependencies>

sample code

package org.example;

import org.json.JSONObject;
import org.json.XML;

public class Main {
    public static void main(String[] args) {

        String input = "{\"cars\" : [\"BMW\", \"Mercedes\", \"Mazda\"]}";
        String output = convertJSON2XML(input);

        // result : <cars>BMW</cars><cars>Mercedes</cars><cars>Mazda</cars>

    }

    public static String convertJSON2XML(String _content){
        String xmlString = "";
        try{
            JSONObject jsonObject = new JSONObject(_content);
            xmlString = XML.toString(jsonObject);

        }catch(Exception ex){}
        return xmlString;
    }
}

I like the result to be ...

<cars><item>BMW</item><item>Mercedes</item><item>Mazda</item></cars>

Does anyone know how this can be fixed? Thanx ...

1

There are 1 answers

0
Rifat Rubayatul Islam On

This should work if you already know the key of the json array.

package org.example;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;

public class Main {
    public static void main(String[] args) {

        String input = "{\"cars\" : [\"BMW\", \"Mercedes\", \"Mazda\"]}";
        String output = convertJSON2XML(input);

        // result : <cars>BMW</cars><cars>Mercedes</cars><cars>Mazda</cars>

    }

    public static String convertJSON2XML(String _content){
        String xmlString = "";
        try{
            JSONObject jsonObject = new JSONObject(_content);
            JSONArray cars = jsonObject.getJSONArray("cars");
            xmlString = XML.toString(cars, "item");
            xmlString = XML.toString(xmlString, "cars");
            xmlString = XML.unescape(xmlString);
            System.out.println(xmlString);
        }catch(Exception ex){}
        return xmlString;
    }
}