Android 创建嵌套json字符串
我正在创建json字符串,但无法在嵌套的json字符串中为JSONObject提供标记。 这是我想要的Android 创建嵌套json字符串,android,json,arrays,jsonobject,Android,Json,Arrays,Jsonobject,我正在创建json字符串,但无法在嵌套的json字符串中为JSONObject提供标记。 这是我想要的 "User": [ { "User1": { "name": "name1", "Address": "add1", "user_detail": { "Qualification": B.E,
"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添加标记。您可以将所需的JSON字符串传递给JSONObject构造函数来完成这项工作。请看一下当前字符串包含JSONObject的JSONArray,而不是作为根元素的JSONObject。您可以通过以下方式在java中创建当前Json字符串:
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);
//....
只需将问题中提到的整个JSON字符串传递到string对象中,并将其传递给JSONObjectString字符串。在您的例子中,“user1”应该是包含整个JSON字符串的字符串对象。。。jsonArray.putuserObj;jsonArray.putuser;似乎它正在工作…测试它