将字符串从Web服务转换为JSON数组

时间:2016-12-27 13:04:58

标签: java json jsonapi-resources

我想将此Web服务字符串转换为JSONArray,但它似乎有问题,尽管我已经验证了它。

[
 {
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 1,
"workingHours": [],
"email": "ayman.daraghmah@exalt.ps",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "ayman.daraghmah@exalt.ps"
},
{
"hireDate": null,
"homePhoneNumber": null,
"gender": null,
"city": null,
"mobileNumber": null,
"idNumber": 123,
"religion": null,
"leftOver": 1,
"annualVacations": 5,
"dob": null,
"name": null,
"rank": 0,
"id": 11,
"workingHours": [],
"email": "aymandaraghmah@gmail.com",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "aymandaraghmah@gmail.com"
}
]

我的代码:

JSONArray js = new JSONArray(payload);

有效负载的格式应该是什么来创建JSONArray?

2 个答案:

答案 0 :(得分:1)

查看代码看起来应该有效。以下示例为我工作(JSON被视为用于测试的字符串)。

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {

public static void main(String[] args) throws JSONException {
    String test = "[{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 1,\"workingHours\": [],\"email\": \"ayman.daraghmah@exalt.ps\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"ayman.daraghmah@exalt.ps\"},{\"hireDate\": null,\"homePhoneNumber\": null,\"gender\": null,\"city\": null,\"mobileNumber\": null,\"idNumber\": 123,\"religion\": null,\"leftOver\": 1,\"annualVacations\": 5,\"dob\": null,\"name\": null,\"rank\": 0,\"id\": 11,\"workingHours\": [],\"email\": \"aymandaraghmah@gmail.com\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"aymandaraghmah@gmail.com\"}]";

    JSONArray jsonArray = new JSONArray(test);

    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
        System.out.println(explrObject.getString("username"));

    }
  }
}

答案 1 :(得分:0)