简体   繁体   English

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

[英]How to read JSON file with Arrays and Objects in Java

I'm trying to read a file which is fetched from Opentdb and access data from only specific keys. 我正在尝试读取从Opentdb获取的文件,并且仅从特定键访问数据。

I've tried all of the given methods which includes GSON and Json Simple but ended up having errors. 我已经尝试了所有给定的方法,包括GSON和Json Simple,但是最终出现了错误。

Here's my JSON: 这是我的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"
      ]
    }, 

I want to access only category, difficulty, question , correct_answer and incorrect_answers . 我只想访问类别,难度,问题,正确答案和不正确答案

excample for you 给你的例子

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();
    }

and

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM