0

I trying to create the code which generates the JSON data which should look like this

{
  "Main": [
    {
      "prim": "Hello ",
      "secon": [
        {
          "ads": "A Message"
        }
      ]
    }
  ]
}

The code I am trying with is generating like below

{
  "Main": [
    {
      "prim": "Hello"
    },
    {
      "secon": [
        {
          "ads": "A Message"
        }
      ]
    }
  ]
}

Code:

JSONObject prim = new JSONObject();
prim.put("prim", Hello");

JSONObject ads = new JSONObject();
ads.put("ads", "A Message");

JSONArray seconArray = new JSONArray();
seconArray.put(ads);

JSONObject secon = new JSONObject();
secon.put("secon", seconArray);

JSONArray Main = new JSONArray();
Main.put(prim);
Main.put(secon);

JSONObject jsonObj = new JSONObject();
jsonObj.put("Main", Main);

JSONArray topJson = new JSONArray();
topJson.put(jsonObj);
System.out.println(topJson.get(0).toString());

How to remove the unnecessary brackets and create the intended Json data?

1 Answer 1

3

Instead of:

 secon.put("secon", seconArray);

Try:

 prim.put("secon", seconArray);

And remove:

 Main.put(secon);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution. I got where I was missing

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.