2

Using Volley in my Android project, I am getting a json response like:

{
    "value1": 1,
    "value2": aaa,
    "subvalues": [
    {
        "value1": 297,
        "value2": 310,
        "class3": {
            "name": "name1",
            "id": 1,
            "value": 32            
          }
    },
    ...
    ]
}

I need to deserialize it to pojo using Gson. Classes are:

class1:

public class class1 {
    private int value1;
    private String value2;
    private List<class2> vals;

    public class class2 {
        private int value1;
        private int value2;
        private class3 c3;
   }
}

class3:

public class class3 {
    private String name;
    private int id;
    private int value;
}

After calling

Gson g = new Gson();
class1 c1 = g.fromJson(jsonString, class1.class);

I have only value1 and value2 of class1 filled. List remains null all the time. How can I fix this?

4 Answers 4

6

You need to change:

private List<class2> vals;

to:

private List<class2> subvalues;

If you would like to keep vals field original name you can use SerializedName annotation:

public class class1 {
    private int value1;
    private String value2;

    @SerializedName("subvalues")
    private List<class2> vals;

    ...
}

Here you can find more information.

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

Comments

4

change private List<class2> vals; to private List<class2> subvalues

Comments

0

It's because in JSON your referring as subvalues and in java object your field name as vals. change it to subvalues it'll work.

Comments

0

As the other answers state, you're not naming your variables correctly for gson to be able to deserialize properly. Note that you seemingly have a typo in your returned json as well in class two, referring to calss3 instead of class3.

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.