0

Using Gson, I am trying to parse below json, but getting null pointer exception. Please find below class objects to load json output.

json file:

{
  "q1": {
    "question": "Which one is correct team name in NBA?",
    "options": [
      "New York Bulls",
      "Los Angeles Kings",
      "Golden State Warriros",
      "Huston Rocket"
    ]
  }
}

Data class to load q1:

public class Data {
    Q1 q;
}

Q1 class to load json data inside q1:

public class Q1 {

    String question;
    List<String> options;
    String answer;

}

Runner class to parse the data:

public class ParseData {

    public static void main(String[] args) throws IOException {

        String dataAsString = new 
        String(Files.readAllBytes(Paths.get("data.json")));
        System.out.println(dataAsString);

        Gson gson = new Gson();
        Data data = gson.fromJson(dataAsString, Data.class);
        System.out.println("printing question ... "+data.q.question);

    }

}

Can someone please help, thanks in advance.

1
  • Change variable name of Q1 in your Data class to q1. Commented Apr 17, 2019 at 6:06

2 Answers 2

1

You need to change your Q1 q at your Data class to Q1 q1.

Sign up to request clarification or add additional context in comments.

Comments

0

your class object should be same as your json key. change your object from q to q1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.