Hey-men-whatsup Hey-men-whatsup -5 years ago 122
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();
JSONArray jsonArray = new JSONArray(datafromServer );

and came accross to this exception :

org.json.JSONException: Value
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) :


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


Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download