Java 为JsonArray中的对象命名(标题)
我想将以下数据发送到服务器。它包含JSONObject的JsonArray,如下所示Java 为JsonArray中的对象命名(标题),java,json,Java,Json,我想将以下数据发送到服务器。它包含JSONObject的JsonArray,如下所示 { "users":[ {"user-1":{ "Name":"Amit", "Age":"32", "Gender":"male", "Hobby":"Cricket" } "user-2":{ "Name":"Subodh",
{
"users":[
{"user-1":{
"Name":"Amit",
"Age":"32",
"Gender":"male",
"Hobby":"Cricket"
}
"user-2":{
"Name":"Subodh",
"Age":"30",
"Gender":"male",
"Hobby":"Chess"
}
"user-3":{
"Name":"Mala",
"Age":"27",
"Gender":"female",
"Hobby":"Singing"
}
}
]
}
这就是我为同样的代码编写json代码的方式
JSONObject userObject = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject user1 = new JSONObject();
try {
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("Name", "Subodh");
user2.put("Age", "30");
user2.put("Gender", "Male");
user2.put("Hobby", "Chess");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user3 = new JSONObject();
try {
user3.put("Name", "Mala");
user3.put("Age", "27");
user3.put("Gender", "Female");
user3.put("Hobby", "Singing");
} catch (JSONException e) {
e.printStackTrace();
}
userArray.put(user1);
userArray.put(user2);
userArray.put(user3);
try {
userObject.put("user", userArray);
} catch (JSONException e) {
e.printStackTrace();
}
但是,我不知道如何在JsonArray中为对象(user-1、user-2等)命名。有人能帮忙吗。我想为JsonArray中的每个JsonObject指定标题。在每个JsonObject创建中编写JSON对象名称,如下所示:-
JSONObject jsonobj = new JSONObject("user1 ");
try {
jsonobj.put("Name", "Amit");
jsonobj.put("Age", "32");
jsonobj.put("Gender", "Male");
jsonobj.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
您的JSON无效
JSON数组中的元素没有键(您称之为“标题”)。只有JSON对象中的值才有键
因此,这是错误的:
{
"users": [
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
]
}
虽然这是正确的:
{
"users": {
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
}
}
要获得正确的JSON,只需使用JSONObject
而不是JSONArray
:
JSONObject resultObject = new JSONObject();
JSONObject usersObject = new JSONObject();
JSONObject user1 = new JSONObject();
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
usersObject.put("user-1", user1);
// repeat for user 2, 3, 4, ...
resultObject.put("users", usersObject);
哦。。我得到了它。在JsonArray上犯了错误。谢谢你的更正。