我得到了以下 json:
{
"ID": "1234567",
"dangereousCargo": true,
"numberOfPassangers": 164,
"cargo": [
{
"type": "Oil",
"amount": 8556
},
{
"type": "Chemicals",
"amount": 5593
}
]
}
从this问题中,我了解到可以从jsonObject中获取cargoList(如果该列表包含某种类型的对象)。但是如何从该列表中获取单独的 CargoObjects 呢?
+jsonstring 的变量名称必须与我的 CargoClass 中的变量名称相对应吗?如果 jsonObject 仅包含 type 和 amount 而我的 CargoClass 有更多属性怎么办?
最佳答案
您可以迭代抛出表示您的 cargo 列表正在执行的JSONArray
(未测试)
JSONObject json = new JSONObject(jsonString);
JSONArray cargoList = json.getJSONArray("cargo");
for(int i=0; i< cargoList.length(); i++) {
JSONObject cargo = cargoList.getJSONObject(i);
//Do something with cargo
}
关于java - 如何从 jsonstring 中的列表解析自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33611539/