如何在Java中使用数组和对象读取JSON文件

时间:2019-06-14 15:57:55

标签: java json jsonreader

我正在尝试读取从Opentdb获取的文件,并且仅从特定键访问数据。

我尝试了所有给定的方法,包括GSON和Json Simple,但最终出现了错误。

这是我的JSON:

    {
  "response_code": 0,
  "results": [
    {
      "category": "Sports",
      "type": "multiple",
      "difficulty": "easy",
      "question": "Which of the following sports is not part of the triathlon?",
      "correct_answer": "Horse-Riding",
      "incorrect_answers": [
        "Cycling",
        "Swimming",
        "Running"
      ]
    },
    {
      "category": "Sports",
      "type": "multiple",
      "difficulty": "easy",
      "question": "Which English football club has the nickname \u0026#039;The Foxes\u0026#039;?",
      "correct_answer": "Leicester City",
      "incorrect_answers": [
        "Northampton Town",
        "Bradford City",
        "West Bromwich Albion"
      ]
    }, 

我只想访问类别,难度,问题,正确答案和不正确答案

1 个答案:

答案 0 :(得分:0)

excample为您

try {
        URL resource = App.class.getClassLoader().getResource("info.json");
        System.out.println(resource.toString());
        FileReader reader = new FileReader(resource.getFile());

        // Read JSON file
        Object obj = jsonParser.parse(reader);

        JSONArray infoList = (JSONArray) obj;
        System.out.println(infoList);

        Information i = new Information();

        List<Information> info = i.parseInformationObject(infoList);

        saveInformation(info);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

List<Information> parseInformationObject(JSONArray infoList) {
    List<Information> in = new ArrayList<>();

    infoList.forEach(emp -> {

        JSONObject info = (JSONObject) emp;

        String id = info.get("id").toString();
        String state = info.get("state").toString();
        String type = null;
        if (info.get("type") != null) {
            type = info.get("type").toString();
        }
        String host = null;
        if (info.get("host") != null) {
            host = info.get("host").toString();
        }
        long timestamp = (long) info.get("timestamp");

        in.add(new Information(id, state, type, host, timestamp));

    });
    return in;
}