首页 > 解决方案 > 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 

标签: javajson

解决方案


试试 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":""}]

如果有任何不清楚的地方,请询问。


推荐阅读