How can i add square brackets to json, after converting from xml, using java

Viewed 280

I have the following code with me.

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

public class Xml2Json {
    public static void main(String[] args) {
    String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
        JSONObject jsonObject = XML.toJSONObject(xmlString);
        System.out.println(jsonObject);
}}

It produces the following output:

{"users":{"report":{"sub":"eng","score":30},"user":{"name":"test1","age":20}}}

But what I actually need is with square brackets only one some of the tags/elements, as you can view on below JSON as expected output:

[{"users":[{"report":[{"sub":"eng","score":30}],"user":{"name":"test1","age":20}}]}]
1 Answers

You can change your code to:

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

public class XmlToJson {
    public static void main(String[] args) {
        String xmlString = "<users><user name=test1 age=20></user><report sub=eng score=30></report></users>";
        JSONObject jsonObject = XML.toJSONObject(xmlString);
        jsonObject.getJSONObject("users").put("report",new JSONArray().put(jsonObject.getJSONObject("users").getJSONObject("report")));
        jsonObject.put("users",new JSONArray().put(jsonObject.getJSONObject("users")));
        JSONArray jsonArray =  new JSONArray().put(jsonObject);
        System.out.println(jsonArray);
    }
}

Output:

[{"users":[{"report":[{"sub":"eng","score":30}],"user":{"name":"test1","age":20}}]}]
Related