2

I am using org.json to convert an xml to json using below code snippet.Unfotunately, there is a structure called "countries" which is supposed to be an array, but can have only 1 country sometimes. In such cases, array is not getting disaplyed instead "countries" is showing up under {} instead of [{}] or [].

        JSONObject xmlJSONObj = XML.toJSONObject(xsltresponse);
        return xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);

output i am getting is with after json conversion is:

         {
          "data":{
              "name":"Microsoft",
               "date":"today",
                "countries":{
                      "name:"AN"
                         }}}

Instead of getting below output

             {
            "data":{
              "name":"Microsoft",
               "date":"today",
                "countries":[{
                      "name:"AN"
                         }]
                         }}

How do i fix it?

1 Answer 1

1

I used this to arrive at solution, this works fine. I will mark it as accepted answer. Please let me know other wise.

   JSONObject xmlJSONObj = XML.toJSONObject(response);
   JSONArray jsonArray = new JSONArray();
  JSONObject data = xmlJSONObj.getJSONObject("data");
  JSONObject objArr = data.optJSONObject("countries");
  if (objArr != null) {
    jsonArray.put(objArr);
    data.putOpt("countries", jsonArray);
       }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.