如何创建一个嵌套的 JSONObject

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

How to create a nested JSONObject

问题

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

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

要创建的JSON主体消息:

{
    "body": {
        "studentInfo": {
            "name": "ALEX JAMES",
            "id": "22284666",
            "age": "13"
        }
    }
}
英文:

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

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

JSON body message to be created:

{
    "body": {
        "studentInfo": {
            "name": "ALEX JAMES",
            "id": "22284666",
            "age": "13"
        }
    }
}

答案1

得分: 2

可以嵌套对象

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);
英文:

you can nest objects

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);

答案2

得分: 2

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

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

输出

{"body": {"studentInfo": {
    "name": "Alex James",
    "id": "22284666",
    "age": 13
}}}

repl.it上测试它。

英文:

This standalone example seems to do what you want:

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

Output

{"body": {"studentInfo": {
    "name": "Alex James",
    "id": "22284666",
    "age": 13
}}}

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:

确定