我有这个String data = "[ {\"pname\":\"7\",\"qty\":\"222\"}, {\"pname\":\"8\",\"数量\":\"5\"}, {\"pname\":\"10\",\"数量\":\"65\"}, ]";
它位于数组列表中,我想将它们放在每个循环的变量上并将其保存到数据库中,但现在我执行此代码是出于调试目的,因为在代码的第一个循环中,它应该输出“qty” value 但它是一个像这样的 null {"pname":"7","qty":"222"} null
但在下一次循环运行时它会输出这个 {"pname ":"8","qty":"5"} 222
似乎在第二个循环中,第一个对象的数量值在第二个循环中被取,最终的输出是这样的
{"pname":"7","qty":"222"} null {"pname":"8","qty":"5"} 222 {"pname":"10","qty “:”65“} 5
这是我的代码
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(txtQty).append(" ");
}
}
有人可以帮我解决这个问题吗?任何帮助将不胜感激,谢谢!!!
最佳答案
您为 txtQty 分配了错误的值,而不是 JSONObject 中的当前值:
HashMap Put
方法(来自文档):
返回:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
这就是为什么你第一次尝试时得到 null,第二次尝试时得到 222。
以下代码将为您提供所需的结果:
String data = "[ {\"pname\":\"7\", \"qty\":\"222\"}, {\"pname\":\"8\", \"qty\":\"5\"}, {\"pname\":\"10\", \"qty\":\"65\"}, ]" ;
HashMap<String, String> item = new HashMap<String, String>();
JSONArray jsonArray = new JSONArray(data);
JSONObject jsonObject = new JSONObject();
ArrayList<HashMap> mylist = new ArrayList<HashMap>();
String txtPname = "", txtQty = "";
if (jsonArray == null) {
System.out.println("json is empty");
} else {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
txtPname = item.put("pname", jsonObject.getString("pname"));
txtQty = item.put("qty", jsonObject.getString("qty"));
output.append(jsonObject).append(" ");
output.append(jsonObject.getString("qty")).append(" ");
}
}
关于java - JSONObject getString 在第一次运行时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424975/