简体   繁体   中英

Creating a JSON object and send it to PHP(server)

I am trying to create a nested JSON object similar to the below one.

{
"Gender":{
  "male":"yes",
      "female":"yes",
   },
   "Role":{

     "RoleA":"yes",
     "RoleB":"yes"
  },
[…]
}

Tried below code but,I am able to insert only one key-value pair.

JsonObject innerObject = new JsonObject();
innerObject.addProperty("Male", "yes");
innerObject.addProperty("Female", "yes");

JsonObject jsonObject = new JsonObject();
jsonObject.add("Gender", innerObject);

The above code would just create the Gender array. How do I create the entire array (as mentioned above)?

Why work with JSON directly? JSON's an encoding/transport format, not something you ever work with directly. Just create a native data structure in whatever language you're working when, then use that language's equivalent of json_encode() to do the translation for you.

Since you've tagged this PHP, why not just

$data = array(
   'Gender' => array('male' => 'yes', 'female' => 'yes'),
   'Role' => array(etc...etc...),
    etc...etc...
);
echo json_encode($data);

Poof. One JSON-encoded "object".

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