cannot serialize tree
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
Gson.toJson() does notproperly serialize sublcasses of a generic type that is the same with enclosing type. This woluld be typical for a tree implementation.
TCheck the output of folowing code:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class GsonTreeTest {
static class Base implements java.io.Serializable {
/**
\*
*/
private static final long serialVersionUID = 1L;
String base = "base";
List children = new ArrayList();
}
```
static class Ex extends Base implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String ext = "exr";
}
public static List getObject(List list) {
list.add(new Base());
list.add(new Ex());
return list;
}
public static void main(String[] args){
Base b=new Base();
getObject(b.children);
System.out.println(new Gson().toJson(b));
ArrayList l=new ArrayList();
getObject(l);
System.out.println(new Gson().toJson(l));
b.children=l;
System.out.println(new Gson().toJson(b));
}
```
}
System.out:
{"base":"base","children":[{"base":"base","children":[]},{"base":"base","children":[]}]}
[{"base":"base","children":[]},{"ext":"exr","base":"base","children":[]}]
{"base":"base","children":[{"base":"base","children":[]},{"base":"base","children":[]}]}
if the list is directly serialized the subclass is correctly serialized, but if the list is a member of the base class the subclass is incorrectly serialized.
Contributor guide
Assessment
This issue has not been assessed yet.