Convert a string from web service to JSON array

1.1k views Asked by At

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": "[email protected]",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "[email protected]"
},
{
"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": "[email protected]",
"managers": [],
"alternativeMobileNumber": null,
"activated": true,
"username": "[email protected]"
}
]

My Code:

JSONArray js = new JSONArray(payload);

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

2

There are 2 answers

0
user1622369 On BEST ANSWER

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\": \"[email protected]\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"[email protected]\"},{\"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\": \"[email protected]\",\"managers\": [],\"alternativeMobileNumber\": null,\"activated\": true,\"username\": \"[email protected]\"}]";

    JSONArray jsonArray = new JSONArray(test);

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

    }
  }
}
0
Dipak Thoke On

I would recommend you to follow this link to get your problem solve.

http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html