当前,我正在开发一个学习应用程序,该应用程序使用列表视图和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
答案 0 :(得分:0)
尝试使用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":""}]
如果仍然不清楚,请问。