My code sends a GET request to a server,
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
I get a BufferedReader object that prints,
{
"status": "ERROR",
"errorCode": "MISSING_PARAMS",
"errorMessage": null,
"requestId": "20141014181739_11625805172",
"downstreamModuleErrorCode": null,
"object": [
"activity_code",
"activity_name",
"points",
"frequency",
"strategy",
"vsa_app_access_token"
]
}
I want to get a JSONOBject or a Map from this. I tried converting this into a String and manipulating it. But it's not that easy to do. Please help.
First do it as string. you can use custom librarys for that like
String message = org.apache.commons.io.IOUtils.toString(rd);
or a StringBuilder
StringBuilder sb = new StringBuilder();
String line;
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
Then you can parse it. Since it's an object because of the "{" (array begin and ends with []) you need to create an JSONObject.
JSONObject json = new JSONObject(sb.toString());
then you can access your elements with
//{ "status": "ERROR", "errorCode": "MISSING_PARAMS", "errorMessage": null, "requestId": "20141014181739_11625805172", "downstreamModuleErrorCode": null, "object": [ "activity_code", "activity_name", "points", "frequency", "strategy", "vsa_app_access_token" ]}
json.getString("status");
or the array with
JSONArray jsonArray = new JSONArray(json.getString("object"));
or you use the method getJSONArray()
JSONArray jsonArray = json.getJSONArray("object");
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
JSONArray jsonArray = new JSONArray(builder.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (!json.get("object").equals(null)) {
JSONArray objectJsonArray = json.getJSONArray("object");
for (int i = 0; i < objectJsonArray.length(); i++) {
JSONObject json = objectJsonArray.getJSONObject(i);
}
}
}
Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With