Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize array of objects inside another object using Gson

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?

like image 892
Alexandr Kapshuk Avatar asked Apr 08 '26 08:04

Alexandr Kapshuk


1 Answers

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.

like image 123
Ziem Avatar answered Apr 10 '26 22:04

Ziem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!