Gson fromJson() returns object with null attrubutes

后端 未结 3 1279
醉话见心
醉话见心 2021-01-17 14:58

I\'m trying to create some Java objects using this line:

Quiz currentQuiz = gson.fromJson(json, Quiz.class);

But the all I get is this:

相关标签:
3条回答
  • 2021-01-17 15:22

    Try this...

    JSONObject js = new JSONObject(jsonString);
    for (int i = 0; i < js.length(); i++) {
      JSONObject quiz = js.getJSONObject("quiz");
        for (int j = 0; j < js.length(); j++) {
           String broadcast_dt = quiz.getString("broadcast_dt");
           String ref = quiz.getString("ref");
           JSONArray questions = quiz.getJSONArray("questions");
           for (int k = 0; k < questions.length(); k++) {
            String value = questions.getString(k);
            JSONObject quest = new JSONObject(questions.getString(k));
            int question_number = quest.getInt("question_number");
            String question_text = quest.getString("question_text");
            JSONArray answers = quest.getJSONArray("answers");
            for (int m = 0; m < answers.length(); m++) {
                JSONObject ans = new JSONObject(answers.getString(m));
                Boolean correct_yn = ans.getBoolean("correct_yn");
                String answer_text = ans.getString("answer_text");
            }
        }
    
    }
    
    }
    
    0 讨论(0)
  • 2021-01-17 15:23

    From your json: i see that, at the root level it is something like

    {quiz:{quizObject having ref,etc.,}}

    So, you need to get one level down to start parsing using gson.

    So, try this out,

    JSONObject quizObject = json.get("quiz");
    
    Quiz currentQuiz = gson.fromJson(quizObject.toString(), Quiz.class);
    
    0 讨论(0)
  • 2021-01-17 15:28

    In my case I had deleted

    @SerializedName("OpCode")
    @Expose
    

    parts from my model class which are above the

    private Integer opCode;
    

    line. And so Gson could not parse it and so my attributes were null. When I added those lines it fixed.

    0 讨论(0)
提交回复
热议问题