最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Deserialising a complex object - Stack Overflow

programmeradmin0浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论