android - 从android studio加载多层Json文件不一致
问题描述
我是使用 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
面临的挑战是选择子县值来排除那些对病房至关重要的值。感谢您提供支持
解决方案
使用下面的代码和 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();
}
}
}
推荐阅读
- react-native - 从服务器收到状态码 401: Unauthorized react native mapbox
- python - 删除 Pandas 中大型数据文件的预告片
- node.js - 使用套接字并在套接字侦听器收到它时返回一个值
- c++ - C ++中的线性搜索与二进制搜索实时性能
- amazon-web-services - 具有多个谓词条件的 Glue 的 AWS CloudFormation 模板
- python - 绘制带有适当图例的熊猫数据框
- model - 如何在我的 ssd 初始模型上添加新的检测对象?
- sql - 无法删除或更新父行:外键约束失败 laravel
- centos - 在某些 Centos 7 映像上未使用 cloud-init 初始化网络
- python - 自动将一组 C 常量转换为 C++ 强类型枚举