我是使用json文件的新手,我已经构造了一个分层的json对象,我试图在android studio Toast中显示这些值,但是其中一些是关键值,我不希望它们显示出来,但是它们正在显示过程中,请指导做错了什么
这是json文件的一部分(json数组中的单个对象)
{
"county": "Nyeri",
"subcounty": ["Kieni East", [{
"ward": ["funny", [{
"policestation": ["null"]
}], "kkkkk", [{
"policestation": ["null"]
}]]
}], "Kieni West", [{
"ward": "null"
}], "Mathira East", [{
"ward": ["Magutu", [{
"policestation": ["Magutu", [{
"arbitrator": ["null"]
}], "Magutu ps", [{
"arbitrator": ["null"]
}], "Kagochi PS", [{
"arbitrator": ["null"]
}]]
}], "Iriani", [{
"policestation": ["null"]
}], "Konyu", [{
"policestation": ["null"]
}], "Kirimukuyu", [{
"policestation": ["null"]
}], "Karatina Town", [{
"policestation": ["Kagochi PS", [{
"arbitrator": ["null"]
}], "Gitunduti PS", [{
"arbitrator": ["christopher bundi", "silvester kasanga"]
}]]
}]]
}], "Mukurweini", [{
"ward": "null"
}], "Tetu", [{
"ward": ["rulie", [{
"policestation": ["null"]
}]]
}]]
}
这是代码,并试图通过不包括病房列表的键来访问子县
try {
JSONArray jsonArray = new JSONArray (response);
for (int i = 0; i < jsonArray.length (); i++) {
JSONObject jsonObject = jsonArray.getJSONObject (i);
String subcounty = jsonObject.getString ("subcounty");
Toast.makeText (getApplicationContext (), subcounty, Toast.LENGTH_LONG).show ();}//close try and catch follows
面临的挑战是选择子县的值,以免除那些对病房很关键的值。 感谢您提供支持
答案 0 :(得分:0)
通过将阵列修改为正确的格式,即 [{ “ county”:“ Mombasa”, “子县”:[{ “ subcountyname”:“ mtwapa”, “病房”:[{ “ wardname”:“有趣”, “警察局”: [{ “ stationame”:“ Magutu ps”, “仲裁员”:[{ “ arbitratorname”:“ christopher bundi” }] }] }] },{ “ subcountyname”:“ likoni”, “病房”:[{ “ wardname”:“空” }] },{ “ subcountyname”:“ hihi”, “病房”:[{ “ wardname”:“空” }] },{ “ subcountyname”:“ mambo”, “病房”:[{ “ wardname”:“空” }] }] },{ “ county”:“ Kwale”, “子县”:[{ “ subcountyname”:“空” }] }] 然后我可以通过循环从数组访问数据 通过初始数组中的对象。 在这个带有对象子县的级别上,我可以在其中获取数组,,,得到该数组中的对象子县名称,以此类推,为了更清楚起见,请参考Parsing JSON array and object in Android
答案 1 :(得分:0)
使用以下代码和JsonFormat,希望对您有所帮助。
String response = "[{"name":"Country 1", "subs": ["sub1","sub2","sub3"] },{"name":"Country 2", "subs": ["subWest1","subWest2","subWest3"] }]";
try{
JSONArray mainList = new JSONArray(response);
ArrayList<String> countries = new ArrayList<>();
ArrayList<String> subs = new ArrayList<>();
for (int a=0;a<mainList.length();a++){
JSONObject object=mainList.getJSONObject(a);
countries.add(object.getString("name"));
subs.add(object.getString("subs"));
}
setAdapterForCountries(countries);
}catch(JSONException e){
e.printStackTrace();
}
在项目选择回调上执行此操作
////On Item Select
JSONArray subCountries = new JSONArray(subs.get(selectedItemPosition));
setSubCountiresAdapter(subCountries);
这是从该JSONArray获取字符串列表的方法。
private void setSubCountiresAdapter(JSONArray subs){
ArrayList<String> subsNames = new ArrayList<>();
for (int a=0;a<subs.length();a++){
try {
subsNames.add(subs.getString(a));
} catch (JSONException e) {
e.printStackTrace();
}
}
}