gpt4 book ai didi

java - Json解析listview自定义适配器

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:06 25 4
gpt4 key购买 nike

目前我正在开发一个学习应用程序,支持使用 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":""}]}

我需要 ListView 像这样显示。

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

如果有任何不清楚的地方,尽管问。

关于java - Json解析listview自定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56088884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com