我正在为Android开发一个应用程序,该应用程序调用了一个返回带有JSON作为参数的json的网络服务,我可以浏览所有设置并轻松保存它们。
问题是当我获取在JSON对象中返回的数组时。
JSON范例:
[{"codigoArticulo":"0001","nombreArticulo":"CHULETAS DE CORDERO","factorVentasDefecto":"KG","precio":21.95,"factoresDeVenta":["KG","UN"]},{"codigoArticulo":"0007","nombreArticulo":"FALDETA DE CORDERO","factorVentasDefecto":"KG","precio":11.95,"factoresDeVenta":["KG","FL"]}]
我可以轻松保存“ codigoArticulo”,“ nombreArticulo”,“ factorVentasDefecto”和“ precio”,但是我不知道如何保存“ factoresDeVenta”。
我有此代码:
JSONArray resparray = new JSONArray(JSONdevuelto);
for (int i = 0; i < resparray.length(); i++) {
JSONObject respJSON = resparray.getJSONObject(i);
int IDArticulo = respJSON.getInt("codigoArticulo");
String NombreArticulo = respJSON.getString("nombreArticulo");
String FactordeVenta = respJSON.getString("factorVentasDefecto");
int PrecioArticulo = respJSON.getInt("precio");
}
我如何在一个数组中保存“ factoresDeVenta”上的变量?
我尝试
String[] Factores = respJSON.getJSONArray("factoresDeVenta");
但由于类型不兼容而无法使用。
我需要阵列才能稍后成为Spinner
谢谢。
最佳答案
factoresDeVenta
是JSONObject中的JSONArray,因此您将需要使用getJSONArray
或optJSONArray
并使用循环从JSONArray获取值:
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
String str_value=jArray.optString(i); //<< jget value from jArray
}