Reputation: 597
I have a JSON text as response from a web API:
{
"code": 0,
"message": "Success",
"data": {
"invoiceId": "26825",
"additionService": [
2
],
"invoiceStatusTxt":"OK"
}
}
I'm using JSONParser
to get a JSONArray
from the additionService
key. But, it is showing a JSON error. My code is:
JSONObject RES = JSONParser.getJSON(URL_API);
JSONArray ob = RES.getJSONObject("data").getJSONArray("additionService");
The error messages are as follows:
W/System.err﹕ org.json.JSONException: No value for additionService
W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:355)
W/System.err﹕ at org.json.JSONObject.getJSONObject(JSONObject.java:574)
i has used json parser before, when i get value from key invoiceId.. it work, i have problem with additionService –
Upvotes: 3
Views: 879
Reputation: 1082
You can also use JSONParser parse method
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(URL_API);
JSONObject dataObject= (JSONObject) jsonObject.get("data");
JSONArray additionService = (JSONArray) dataObject.get("additionService");
In your case I think there is type cast error.
Upvotes: 0
Reputation: 11620
Your input data is corrent. I assume that your problem lies somewhere else, either your input String is wrong, or your library.
Little test that works (JDK7):
@Test
public void testJson() {
String URL_API = "{\"code\": 0,\"message\": \"Success\",\"data\": {\"invoiceId\": \"26825\",\"additionService\": [2],\"invoiceStatusTxt\":\"OK\"}}";
JSONObject RES = new JSONObject(URL_API);
JSONArray ob = RES.getJSONObject("data").getJSONArray("additionService");
System.out.print(ob); // prints [2]
}
My pom.xml dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
Upvotes: 0
Reputation: 2507
I tried it this way. Seems to be working:
String str = "{\"code\":0,\"message\":\"Success\",\"data\":{\"invoiceId\":\"26825\",\"additionService\":[2],\"invoiceStatusTxt\":\"OK\"}}";
JSONObject obj=(JSONObject) JSONValue.parse(str);
JSONObject data = (JSONObject) obj.get("data");
JSONArray additionService = (JSONArray) data.get("additionService");
System.out.println(additionService);
Upvotes: 1
Reputation: 16031
The exception is thrown at the getJSONObject("data")
call, so the data field is empty. You should make an #isNull()
check on the value returned by #getJsonObject()
. Then, if it exists, get the array from it.
Upvotes: 0