Read JsonAdapter Annotation From Parent Inteface
- Dominant language
- Java
- Stars
- 24.2k
- Forks
- 4.5k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 12
Description
This is sort of a feature request and sort of just asking for other approaches of potentially handling this.
There are a couple of design choices that we have made for specific reason that I won't go into, but there are a few things to note about our use case:
* We use interfaces for our model objects
* It is feasible that a consumer of our API might provide their own implementation of that model object or use a default one that we provide
For this reason, serialization has always been a bit difficult because the interface is not a reliable contract for serialization (what are the default implementation field names, etc.) and those likely wouldn't work with other implementations of the model object, etc.
For that reason, I was hoping to provide on the interface a default TypeAdapter that serializes to the default instance of the object. This would allow for implementations of the interface to be able to get back to an instance of the object if they didn't have any additional logic that they were wanting.
I looked at JsonAdapter, and it seems to provide what I'm looking for, it just does not get pulled from the interface.
```java
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class TestScenario
{
@JsonAdapter(ATypeAdapter.class)
public interface A
{
String getValue();
}
public static class B implements A
{
@Override
public String getValue()
{
return "B class";
}
}
@JsonAdapter(ATypeAdapter.class)
public static class C implements A
{
@Override
public String getValue()
{
return "C class";
}
}
public class ATypeAdapter extends TypeAdapter
{
@Override
public void write(JsonWriter out, A value) throws IOException
{
System.out.println(value.getValue());
}
@Override
public A read(JsonReader in) throws IOException
{
return null;
}
}
public static void main(String[] args)
{
Gson gson = new Gson();
gson.toJson(new B()); // does not print
gson.toJson(new C()); // does print
}
}
```
In the above example, B class shows that the JsonAdapter annotation is not getting pulled from the interface. The C class shows that the annotation and the TypeAdapter do work, but only if it's on the implementation object.
Basically, I'm looking for a way to default in the serialization of all implementations of an interface unless the consumer chooses to specifically override it (which could be probable if they are implementing multiple interfaces).
Contributor guide
Assessment
This issue has not been assessed yet.