【问题标题】:How to iterate Node.js database query results in Java/ Android如何在 Java/Android 中迭代 Node.js 数据库查询结果
【发布时间】:2019-02-09 14:50:45
【问题描述】:

我在数据库中查询了一个表,得到了以下结果:

{"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" :假}

所有这些都在来自 Node.js 服务器的 Json 中。

如何迭代

提前谢谢大家。

以下尝试中断:

 // 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();
    }
}

出现错误:

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

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

【问题讨论】:

    标签: java android json node.js iteration


    【解决方案1】:
    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();
        }
    }
    

    【讨论】:

    • 谢谢@morteza-jalambadani。我用了你的答案,效果很好。很抱歉回复晚了,并且很晚才接受您的回复。我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多