Skip to content

[bug] sub class field missing during serialization if collection's element type is a WildcardType #1870

@cnzhujie

Description

@cnzhujie

I am serializing a list like this:

List<? extends TestBeanBase> list1;
list1.add(new TestBeanSub());    // TestBeanSub is a child class of TestBeanBase

I find that the fields of TestBeanSub is missed in the serialized json.

You can try my example code:

    @Test
    public void testList() {
        List<TestBeanBase> list = new ArrayList<>();

        //base class
        TestBeanBase baseBean = new TestBeanBase();
        baseBean.a = "1";
        list.add(baseBean);

        //sub class
        TestBeanSub subBean = new TestBeanSub();
        subBean.a = "1";
        subBean.b = "2";//b is a field declared in sub class, this field value is missed during serialization
        list.add(subBean);

        TestBeanList beanList = new TestBeanList();
        beanList.list1 = list;

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(beanList));
    }

    public static class TestBeanList {
        public List<? extends TestBeanBase> list1; //element type is a WildcardType
    }

    public static class TestBeanBase {
        public String a;
    }

    public static class TestBeanSub extends TestBeanBase {
        public String b;
    }

Output json :

{
  "list1": [
    {
      "a": "1"
    },
    {
      "a": "1"   //field b is missed
    }
  ]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions