Prathamesh Talathi
Prathamesh Talathi

Reputation: 195

how to add Json header in json array parsed from Java Object

i found many examples to parse java object to Json. Thanks for that.But i have one issue, i want Json in following format

{
  "parent":
  {
    "sub-parent-1":
    {
      "child-1": 1,
      "child-2": 2
    },
    "sub-parent-2":
    {
      "child-2": 3
    }
  }
}

Is it possible with java. Please answer.Thanks in advanced..

Upvotes: 2

Views: 3271

Answers (2)

Prathamesh Talathi
Prathamesh Talathi

Reputation: 195

I have created class for parent and pass child to it. And convert that parent class into Json using Gson.

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Create Current Json String as in Java :

    JSONObject parent = new JSONObject();
    JSONObject subparentone = new JSONObject();

    JSONObject subparenttwo = new JSONObject();

    subparentone.put("child-1", "1");
    subparentone.put("child-2", "2");

    subparenttwo.put("child-2", "3");

    parent.put("sub-parent-1", subparentone);
    parent.put("sub-parent-2", subparenttwo);

   JSONObject finalparent = new JSONObject();
   finalparent.put("parent", parent);

and finalparent JsonObject output as:

{
  "parent": {
    "sub-parent-1": {
      "child-1": 1,
      "child-2": 2
    },
    "sub-parent-2": {
      "child-2": 3
    }
  }
}

Upvotes: 7

Related Questions