Hey-men-whatsup Hey-men-whatsup - 5 months ago 9
JSON Question

Retrieving JSON in android with single line object structure

I'm quite new to JSON and it's operation I was trying to retrieve JSON from server

datafromServer = bufferedReader.readLine();
inputStream.close();
JSONArray jsonArray = new JSONArray(datafromServer );


and came accross to this exception :


org.json.JSONException: Value
{"last_name":"Hicks","id":18,"email":"dwaynehicks@usssulaco.com","first_name":"Dwayne"}
of type org.json.JSONObject cannot be converted to JSONArray


So I found this answer :

JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("contacts");

for (int i = 0; i < Jarray.length(); i++) {
JSONObject Jasonobject = Jarray.getJSONObject(i);


Now, the problem is, in the answer, OP had object formation of :

"contacts": [{
.....
.....

]


in this JSON. While I get formation of (no key mapped to this line) :

{"last_name":"Hicks","id":18,"email":"dwaynehicks@usssulaco.com","first_name":"Dwayne"}


So how I modified this line
*JSONArray Jarray = object.getJSONArray("contacts");*
?
I don't have such key.

Thanks

Answer

You don't need a JSONArray you can just get the data from the JSONObject like this:

JSONObject jsonObject = new JSONObject(result);
String lastName = jsonObject.getString("last_name");
int id = jsonObject.getInt("id");
String email = jsonObject.getString("email");
String firstName = jsonObject.getString("first_name");