0
votes

I query a table in a database and got the following results :

{"command":"SELECT","rowCount":4,"oid":null,"rows":[{"id":1,"title":"Cheese","primary_author":"9.99"},{"id":2,"title":"Cheese","primary_author":"9.99"},{"id":3,"title":"Cheese","primary_author":"9.99"},{"id":4,"title":"Cheese","primary_author":"9.99"}],"fields":[{"name":"id","tableID":9408343,"columnID":1,"dataTypeID":23,"dataTypeSize":4,"dataTypeModifier":-1,"format":"text"},{"name":"title","tableID":9408343,"columnID":2,"dataTypeID":1043,"dataTypeSize":-1,"dataTypeModifier":104,"format":"text"},{"name":"primary_author","tableID":9408343,"columnID":3,"dataTypeID":1043,"dataTypeSize":-1,"dataTypeModifier":104,"format":"text"}],"_parsers":[null,null,null],"RowCtor":null,"rowAsArray":false}

All this is in Json from a Node.js server.

How can I go about iterating the rows?

Thank you all in advance.

The following attempt breaks:

 // response
Log.v("MyApp", response);

JSONArray json = null;
try {
    json = new JSONArray(response);
} catch (JSONException e) {
    e.printStackTrace();
}

for (int i = 0; i < json.length(); i++) {
    JSONObject e;
    try {
        e = json.getJSONObject(i);
        Log.v("MyApp", "ID  : " + e.getString("id"));

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

with the error :

java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference  

at

for (int i = 0; i < json.length(); i++) {
1

1 Answers

2
votes
Log.v("MyApp", response);

JSONObject json = null;
try {
    json = new JSONObject(response);
} catch (JSONException e) {
    e.printStackTrace();
}

JSONArray jArr = json.getJSONArray("rows");

for (int i = 0; i < jArr.length(); i++) {
    JSONObject e;
    try {
        e = jArr.getJSONObject(i);
        Log.v("MyApp", "ID  : " + e.getString("id"));

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}