I'm using the Unirest library to parse some JSON I'm getting from a MAshape API. I'm new to making HTTP requests in Java, and I'm having trouble understanding the error.
The function I made is:
public ArrayList<String> httpPost(int year) {
HttpResponse<String> response = null;
try {
response = Unirest.post("https://--------.p.mashape.com/v1/calculate/" + year)
.header("X-Mashape-Key", "--------------------------")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
//.field("blabla", "blabla")
.field("filing_status", myFS)
.field("pay_periods", myPP)
.field("pay_rate", getGrossPay())
.field("state", myState)
.asString();
} catch (UnirestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// retrieve the parsed JSONObject from the response
JSONObject myObj = new JSONObject(response);
JSONArray results = new JSONArray();
try {
results = myObj.getJSONArray("annual"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> list = new ArrayList<String>();
if (results != null) {
int len = results.length();
for (int i=0;i<len;i++){
try {
list.add(results.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
I get the error:
org.json.JSONException: JSONObject["annual"] not found
So I outputted the response
variable to a file, and the file had com.mashape.unirest.http.HttpResponse@161b062a
in it. I don't know where that came from.
Just to check, I used hurl.it and the same response I'm putting in to my program yields a successful response:
{
"annual": {
"state": {
"amount": 68232.65
},
"fica": {
"amount": 91800
},
"federal": {
"amount": 418014.8
}
},
"per_pay_period": {
"state": {
"amount": 5686.05
},
"fica": {
"amount": 7650
},
"federal": {
"amount": 34834.57
}
}
}
I tried changing the type of response
from String
to JsonNode
but it didn't work and I don't really know how to work with that anyway. I added all the required libraries as well. Any help?
Use myObj.getJSONObject("annual");