如何创建一个嵌套的 JSONObject

huangapple go评论102阅读模式
英文:

How to create a nested JSONObject

问题

以下是我的代码。我仍需要添加“studentInfo”字段。

  1. JSONObject jo = new JSONObject();
  2. jo.put("name", "ALEX JAMES");
  3. jo.put("id", "22284666");
  4. jo.put("age", "13");

要创建的JSON主体消息:

  1. {
  2. "body": {
  3. "studentInfo": {
  4. "name": "ALEX JAMES",
  5. "id": "22284666",
  6. "age": "13"
  7. }
  8. }
  9. }
英文:

Below is my code. I still need to add the "studentInfo" field.

  1. JSONObject jo = new JSONObject();
  2. jo.put("name", "ALEX JAMES");
  3. jo.put("id", "22284666");
  4. jo.put("age","13")

JSON body message to be created:

  1. {
  2. "body": {
  3. "studentInfo": {
  4. "name": "ALEX JAMES",
  5. "id": "22284666",
  6. "age": "13"
  7. }
  8. }
  9. }

答案1

得分: 2

可以嵌套对象

  1. JSONObject studentInfo = new JSONObject();
  2. studentInfo.put("name", "ALEX JAMES");
  3. studentInfo.put("id", "22284666");
  4. studentInfo.put("age", "13");
  5. JSONObject body = new JSONObject();
  6. body.put("studentInfo", studentInfo);
  7. JSONObject wrapper = new JSONObject();
  8. wrapper.put("body", body);
英文:

you can nest objects

  1. JSONObject studentInfo = new JSONObject();
  2. studentInfo.put("name", "ALEX JAMES");
  3. studentInfo.put("id", "22284666");
  4. studentInfo.put("age","13");
  5. JSONObject body = new JSONObject();
  6. body.put("studentInfo" , studentInfo);
  7. JSONObject wrapper = new JSONObject();
  8. wrapper.put("body" , body);

答案2

得分: 2

这个独立示例似乎可以实现你想要的功能:

  1. import org.json.JSONObject;
  2. class Main {
  3. public static void main(String[] args) {
  4. JSONObject jo = new JSONObject();
  5. JSONObject body = new JSONObject();
  6. jo.put("body", body);
  7. JSONObject si = new JSONObject();
  8. body.put("studentInfo", si);
  9. si.put("name", "Alex James");
  10. si.put("id", "22284666");
  11. si.put("age", 13);
  12. System.out.println(jo.toString(4));
  13. }
  14. }

输出

  1. {"body": {"studentInfo": {
  2. "name": "Alex James",
  3. "id": "22284666",
  4. "age": 13
  5. }}}

repl.it上测试它。

英文:

This standalone example seems to do what you want:

  1. import org.json.JSONObject;
  2. class Main {
  3. public static void main(String[] args) {
  4. JSONObject jo = new JSONObject();
  5. JSONObject body = new JSONObject();
  6. jo.put("body", body);
  7. JSONObject si = new JSONObject();
  8. body.put("studentInfo", si);
  9. si.put("name", "Alex James");
  10. si.put("id", "22284666");
  11. si.put("age", 13);
  12. System.out.println(jo.toString(4));
  13. }
  14. }

Output

  1. {"body": {"studentInfo": {
  2. "name": "Alex James",
  3. "id": "22284666",
  4. "age": 13
  5. }}}

Test it on repl.it.

huangapple
  • 本文由 发表于 2020年10月15日 21:50:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64373063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定