Comment créer un JSONObject imbriqué [duplicate]
Oct 15 2020
Ci-dessous mon code. Je dois encore ajouter le champ "studentInfo".
JSONObject jo = new JSONObject();
jo.put("name", "ALEX JAMES");
jo.put("id", "22284666");
jo.put("age","13")
Corps du message JSON à créer:
{
"body": {
"studentInfo": {
"name": "ALEX JAMES",
"id": "22284666",
"age": "13"
}
}
}
Réponses
1 AliFaris Oct 15 2020 at 14:14
vous pouvez imbriquer des objets
JSONObject studentInfo = new JSONObject();
studentInfo.put("name", "ALEX JAMES");
studentInfo.put("id", "22284666");
studentInfo.put("age","13");
JSONObject body = new JSONObject();
body.put("studentInfo" , studentInfo);
JSONObject wrapper = new JSONObject();
wrapper.put("body" , body);
1 DavidCullen Oct 15 2020 at 14:21
Cet exemple autonome semble faire ce que vous voulez:
import org.json.JSONObject;
class Main {
public static void main(String[] args) {
JSONObject jo = new JSONObject();
JSONObject body = new JSONObject();
jo.put("body", body);
JSONObject si = new JSONObject();
body.put("studentInfo", si);
si.put("name", "Alex James");
si.put("id", "22284666");
si.put("age", 13);
System.out.println(jo.toString(4));
}
}
Production
{"body": {"studentInfo": {
"name": "Alex James",
"id": "22284666",
"age": 13
}}}
Testez - le sur repl.it .