google / google/gson

Data structure that cannot be serialized properly

Open
#1,599 5 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

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 child1Field;
}

@Getter
@Setter
public class Child2 extends Base {
private List 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 child1Field = Lists.asList(1, new Integer[]{1});
((Child1)child1).setChild1Field(child1Field);

Base child2 = new Child2();
child2.setBaseField("child2");
List 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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.