google / google/gson

Serialization of generic types

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

Description

I have a weird issue with the serialisation of generic types. Consider the following program:

```
public class Service {
private static class Characteristic {
private final int id = 1;
}
private static class StringCharacteristic extends Characteristic {
private final String format = "string";
}

private final List> characteristics = Arrays
.asList(new StringCharacteristic(), new Characteristic());

public static void main(String[] args) {
final Gson gson = new Gson();
final Service service = new Service();
System.out.println("service: " + gson.toJson(service));
System.out.println("characteristics only: " + gson.toJson(service.characteristics));
}
}
```

The output (unexpectedly) is :
service: {"characteristics":[{"id":1},{"id":1}]}
characteristics only: [{"format":"string","id":1},{"id":1}]

i.e. the "format" attribute of the string characteristic is omitted when serializing the service object. However if I change the definition of the list to:

```
private final List characteristics = ...;
```

everything works as expected:
service: {"characteristics":[{"format":"string","id":1},{"id":1}]}
characteristics only: [{"format":"string","id":1},{"id":1}]

Any thoughts?

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.