在JsonArray中为对象提供名称(标题)

时间:2018-03-14 05:42:07

标签: java json

我想将以下数据发送到服务器。它包含JsonObject的JsonArray,如下所示。

{
    "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中为Objects(user-1,user-2等)命名。有人可以帮忙做到这一点。我想给JsonArray中的每个JsonObject提供标题。

2 个答案:

答案 0 :(得分:1)

您的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);

答案 1 :(得分:-3)

在每个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();  
  }