我有一个JSON格式的树对象我试图用Gson反序列化.每个节点包含其子节点作为对象类型Node的字段.Node是一个接口,它有几个具体的类实现.在反序列化过程中,如果我不知道该节点属于哪种类型的先验,我如何与Gson通信哪个具体类在反序列化节点时要实现?每个节点都有一个指定类型的成员字段.当对象是序列化形式时,有没有办法访问该字段,并以某种方式将类型传递给Gson?
谢谢!
这是我的Retrofit实例:
@Provides
@Singleton
ApiManager provideApiManager() {
RxJava2CallAdapterFactory rxAdapter = RxJava2CallAdapterFactory.create();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new StethoInterceptor())
.build();
Gson gson = new GsonBuilder().create();
GsonConverterFactory converterFactory = GsonConverterFactory.create(gson);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConstants.BASE_URL)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(rxAdapter)
.client(okHttpClient)
.build();
return retrofit.create(ApiManager.class);
}
Run Code Online (Sandbox Code Playgroud)
模型:
class AbstractMessage {
String id;
}
class TextMessage extends AbstractMessage {
String textMessage;
}
class ImageMessage extends AbstractMessage {
String url;
String text;
}
Run Code Online (Sandbox Code Playgroud)
请求:
@GET("direct/messages")
Observable<List<AbstractMessage>> getMessages(@Header("Authorization") String authHeader, @Body RequestObject request);
Run Code Online (Sandbox Code Playgroud)
执行请求:
apiManager.getMessages(authHeader, requestObject)
.subscribeOn(Schedulers.io()) …Run Code Online (Sandbox Code Playgroud) 我有一个界面
public interace ABC {
}
Run Code Online (Sandbox Code Playgroud)
其实现如下:
public class XYZ implements ABC {
private Map<String, String> mapValue;
public void setMapValue( Map<String, String> mapValue) {
this.mapValue = mapValue;
}
public Map<String, String> getMapValue() {
return this.mapValue
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用实现为的 Gson 反序列化一个类
public class UVW {
ABC abcObject;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试反序列化它时,gson.fromJson(jsonString, UVW.class);它会返回给我null。jsonString 是 UTF_8 字符串。
是不是因为 UVW 类中使用的接口?如果是,我如何反序列化这样的类?