I've got the following interfaces:
public interface SearchResult<T extends IdentifiableOrange> {
....
}
public interface BasicOrange extends IdentifiableOrange {
....
}
public interface OrangeSource extends Identifiable, OrangeDescription, Comparable<OrangeSource> {
....
}
Each interface has at least one implementation that's prefixed with Default
for example, the above interfaces are implemented by DefaultSearchResult
, DefaultBasicOrange
and DefaultOrangeSource
respectively.
public class DefaultBasicOrange{
....
@Expose
Set<OrangeSource> myList;
}
Apologies for being vague because I just added only the minimum required information - the actual attributes/methods lists are very long. Also, the DefaultBasicOrange
includes other attributes that are defined by their interface type. I just showed one as an example.
I have a method that returns SearchResult<BasicOrange> response = search(searchRequest);
And I want to convert this response to Json and I have to be able to read it back as well.
I tried the following to convert to json:
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapterFactory(new GsonValueFieldTypeAdapterFactory())
.create()
var responseJson = gson.toJsonTree(response);
I tried the following to read it back from Json, but it complains about the internal interface usage:
TypeToken<DefaultSearchResult<DefaultBasicOrange>> typeToken = new TypeToken<DefaultSearchResult<DefaultBasicOrange>>() {};
SearchResult<BasicOrange> cachedResponse = gson.fromJson(
responseJson,
typeToken.getType());
The error is:
Caused by: com.google.gson.JsonIOException: Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for this type. Interface name: com.something.OrangeSource
Do I need something like .registerTypeHierarchyAdapter
?