0

我正在创建 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 打标签。

4

2 回答 2

0

您可以将所需的 JSON 字符串传递给 JSONObject 构造函数来完成这项工作。看看这里

于 2014-02-07T08:21:03.357 回答
0

当前字符串包含 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);
//....
于 2014-02-07T08:32:41.320 回答