简体   繁体   中英

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..

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
    }
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM