javajsonjsonapi-resources

Convert a string from web service to JSON array


I want to convert this web service string to JSONArray , but it seems to have a problem , although I've validated it.

[
 {
"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"
}
]

My Code:

JSONArray js = new JSONArray(payload);

what should the format of payload be to create the JSONArray ?


Solution

  • Looking at the code it looks like it should work. Following sample worked for me (The JSON is taken as a string for testing).

    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"));
    
        }
      }
    }