gpt4 book ai didi

java - 如何在 Java/Android 中迭代 Node.js 数据库查询结果

转载 作者:行者123 更新时间:2023-12-02 01:57:05 26 4
gpt4 key购买 nike

我查询数据库中的表并得到以下结果:

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

所有这些都是来自 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++) {

最佳答案

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

关于java - 如何在 Java/Android 中迭代 Node.js 数据库查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com