我正在创建json字符串,但无法在嵌套的json字符串中为JSONObject提供标记。 这就是我想要的东西
"User": [
{
"User1": {
"name": "name1",
"Address": "add1",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
},
{
"User2": {
"name": "name2",
"Address": "add2",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
}
}
]
我已经设法到达这里
{"User":[{"name":"name1","Address":"Add1"}, {"Qualification": "B.E", "DOB":"11/12/1990"}]}
But I am failed to add tag for JSONObject both for USer and user_details
这是我的代码
try {
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
} catch (JSONException je) {
je.printStackTrace();
}
try {
userObj = new JSONObject();
userObj.put("User1", user);
jsonArray = new JSONArray();
jsonArray.put(user);
} catch (JSONException j) {
j.printStackTrace();
}
}
try {
users = new JSONObject();
users.put("User", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
主要的是我不知道,如何给JSONObject提供标签。
答案 0 :(得分:0)
您可以将所需的JSON字符串传递给JSONObject构造函数来完成工作。看看here
答案 1 :(得分:0)
Current String包含JSONObject的JSONArray,而不是JSONObject作为根元素。您可以在java中创建Current Json String:
JSONArray jsonArray = new JSONArray();
// User1 JSONObjects
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
user_obj_one = new JSONObject();
user_obj_one.put("User1",user);
//...same for User2...
...
user_obj_two = new JSONObject();
user_obj_two.put("User2",user_two);
//put in final array :
jsonArray.put(user_obj_one);
jsonArray.put(user_obj_two);
//....