簡體   English   中英

Json解析ListView自定義適配器

[英]Json parse listview custom adapter

目前,我正在開發一個學習應用程序,該應用程序使用列表視圖和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":""}]

如果還有什么不清楚的地方,問一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM