Deserialize array of objects inside another object using Gson

寵の児 提交于 2019-12-24 03:05:35

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/29877979/deserialize-array-of-objects-inside-another-object-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!