1

I'm trying to read a file which is fetched from Opentdb and access data from only specific keys.

I've tried all of the given methods which includes GSON and Json Simple but ended up having errors.

Here's my 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 .

Rai Ansar
  • 11
  • 5

1 Answers1

0

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