java - Json解析listview自定义适配器
问题描述
目前我正在开发一个学习应用程序,它支持使用列表视图和 json 的动态菜单。
我试图实现它,但我无法读取节点 JSON 对象。
private void loadMainMenu() {
try {
FileInputStream inputStream = openFileInput(MainActivity.FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
JSONObject jsonObj = new JSONObject(builder.toString());
String obj = jsonObj.getString("rootNode");
JSONArray jsonArray = new JSONArray(obj);
for (int j = 0; j < obj.length(); j++) {
TitleModel title = new TitleModel(jsonObj.getJSONObject(String.valueOf(j)).toString());
titleArrayList.add(title);
titleAdapter = new TitleAdapter(this, titleArrayList);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
json文件就是这个。
{"Maths":[{"Part":"ክፍል 1","url":""}],"Chemistry":[{"Part":"ክፍል 1","url":""}],"Biology":[{"Part":"ክፍል 1","url":""}],"Physics":[{"Part":"ክፍል 1","url":""}],"History ":[{"Part":"ክፍል 1","url":""}]}
我需要的是列表视图会像这样显示。
Maths
Chemistry
Biology
Physics
History
解决方案
试试 Jackson 框架,你可以在这里找到它:https ://github.com/FasterXML/jackson
它将为您处理文件处理和 JSON 数据结构。您只需要浏览。所需的输出由我的示例代码生成。该框架实际上可以做更多的事情,但一开始,你可以坚持下去。
注意:该文件test.json
位于 src/main/resources/ 下,与此处的 maven 示例项目中使用的一样。随意根据需要调整它。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = null;
try {
node = mapper.readValue(new File(App.class.getClassLoader().getResource("test.json").getPath()), JsonNode.class);
} catch (Exception e) {
// TODO -- handle exception
e.printStackTrace();
}
node.fieldNames().forEachRemaining(System.out::println);
System.out.println(" --- ALTERNATIVELY ---");
node.fields().forEachRemaining( currDiscipline -> {
System.out.println("Menu item: " + currDiscipline.getKey() + " with " + currDiscipline.getValue());
});
}
}
我的结果如下所示:
Maths
Chemistry
Biology
Physics
History
--- ALTERNATIVELY ---
Menu item: Maths with [{"Part":"ክፍል 1","url":""}]
Menu item: Chemistry with [{"Part":"ክፍል 1","url":""}]
Menu item: Biology with [{"Part":"ክፍል 1","url":""}]
Menu item: Physics with [{"Part":"ክፍል 1","url":""}]
Menu item: History with [{"Part":"ክፍል 1","url":""}]
如果有任何不清楚的地方,请询问。
推荐阅读
- asp.net-core - 构建错误 - 命名空间“Microsoft”中不存在类型或命名空间名称“AspNetCore”(您是否缺少程序集引用?
- javascript - 如何更新从函数返回的变量?
- sql - 是否有任何方法或其他方法可以通过带有字符串值的数据表进行排序
- class - Xamarin - 如何将变量传递给视图模型
- javascript - 如何从字符串计算数组元素的计数
- mysql - SQL UNION 查询返回具有列名的第一行
- java - 单击按钮时如何将数据从适配器传递到主活动
- selenium - Specflow - GenerateFeatureFileCodeBehindTask 意外失败
- java - 如何从特定站点 JSOUP 中抓取表数据
- angular - Primeng 表上的虚拟滚动:滚动高度问题