Skip to content

Data structure that cannot be serialized properly #1599

@hanlifei

Description

@hanlifei

Below is the data structure and serialization method I defined.

@Getter
@Setter
public class Base {
	private String baseField;
	private Base child;
}

@Getter
@Setter
public class Child1 extends Base {
	private List<Integer> child1Field;
}

@Getter
@Setter
public class Child2 extends Base {
	private List<Integer> child2Field;
}

public class Test {
	public static void main(String[] args) throws JsonProcessingException {
		Base base = new Base();
		base.setBaseField("base");

		Base child1 = new Child1();
		child1.setBaseField("child1");
		List<Integer> child1Field = Lists.asList(1, new Integer[]{1});
		((Child1)child1).setChild1Field(child1Field);

		Base child2 = new Child2();
		child2.setBaseField("child2");
		List<Integer> child2Field = Lists.asList(2, new Integer[]{2});
		((Child2)child2).setChild2Field(child2Field);

		child1.setChild(child2);
		base.setChild(child1);

		System.out.println(new Gson().toJson(base));
	}
}

I thought that the result I got was like this:

{
    "baseField": "base", 
    "child": {
        "baseField": "child1", 
        "child": {
            "baseField": "child2", 
            "child2Field": [
                2, 
                2
            ]
        }, 
        "child1Field": [
            1, 
            1
        ]
    }
}

But the result I got is like this:

{
    "baseField": "base", 
    "child": {
        "baseField": "child1", 
        "child": {
            "baseField": "child2"
        }
    }
}

I lost the value of childXField.
What is going on here? Is it a data type that does not support such recursive references?

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