英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论