如何在Android中创建此格式的JSON: 因为我将要传递的API将解析JsonArray,然后解析对象. 或者只传递一个json对象可以吗?因为我只需在每个服务调用中插入1个事务.

{
    "student": [
        {
            "id": 1,
            "name": "John Doe",
            "year": "1st",
            "curriculum": "Arts",
            "birthday": 3/3/1995
        },
        {
            "id": 2,
            "name": "Michael West",
            "year": "2nd",
            "curriculum": "Economic",
            "birthday": 4/4/1994
        }
    ]
}

我只知道JSONObject. 就像这个一样.

JSONObject obj = new JSONObject();
try {
    obj.put("id", "3");
    obj.put("name", "NAME OF STUDENT");
    obj.put("year", "3rd");
    obj.put("curriculum", "Arts");
    obj.put("birthday", "5/5/1993");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Any ideas. Thanks

推荐答案

使用以下代码:

JSONObject student1 = new JSONObject();
try {
    student1.put("id", "3");
    student1.put("name", "NAME OF STUDENT");
    student1.put("year", "3rd");
    student1.put("curriculum", "Arts");
    student1.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

JSONObject student2 = new JSONObject();
try {
    student2.put("id", "2");
    student2.put("name", "NAME OF STUDENT2");
    student2.put("year", "4rd");
    student2.put("curriculum", "scicence");
    student2.put("birthday", "5/5/1993");

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


JSONArray jsonArray = new JSONArray();

jsonArray.put(student1);
jsonArray.put(student2);

JSONObject studentsObj = new JSONObject();
    studentsObj.put("Students", jsonArray);



String jsonStr = studentsObj.toString();

    System.out.println("jsonString: "+jsonStr);

Json相关问答推荐

我发现GoFr响应总是包含在数据字段中,如何返回自定义响应?

VBA json按特定属性名称提取所有数据

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

规范化JSON数据

派生类的属性没有得到价值

Powershell 7.2:ConvertFrom-Json - 日期处理

Oracle Apex - 将 JSON 对象分配给变量以返回

Servicestack 返回数组而不是带有数组的对象

如何解决名为 null 的map值

杰克逊 2.0 和 Spring 3.1

apple-app-site-association json 文件是否会在应用程序中更新?

使用 gson 反序列化对象的特定 JSON 字段

jquery用json数据填充下拉列表

在 Rails 3 中处理 JS/ERB 模板中的 JSON

如何使用 SwiftyJSON 将字符串转换为 JSON

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

使用 Python 3 读取 JSON 文件

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

Java HashMap 与 JSONObject

使用 JavaScriptSerializer() 反序列化 JSON 文件