0

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 Answer 1

2
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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @morteza-jalambadani. I used your answer and it works very well. Sorry for the late reply, and for accepting your answer late. I am grateful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.