简体   繁体   English

儿童的序列化和反序列化

[英]Serialization and deserialization of children

Let's assume I have the following structure: 假设我具有以下结构:

abstract class foo{}
class bar1 extends foo{
     int demo1 = 0;
}
class bar2 extends foo{
     int demo1 = 0;
     int demo2 = 0;
}
class bar3 extends foo{}

Usually when I need to send a Json, I use the following code 通常,当我需要发送Json时,我使用以下代码

Gson gson = new Gson()
gson.toJson(bar1);

Recieving end 收货结束

Gson gson = new Gson()
bar1 test = gson.fromJson(gsonString, bar1);

The issue here is that I need to send bar1/bar2/bar3 and get back the original object - Meaning I don't know what the current JSON should be parsed back into . 这里的问题是,我需要发送bar1 / bar2 / bar3并返回原始对象- 意味着我不知道当前的JSON应该解析回什么 Another layer of complexity is added due to the fact that an array of bar1/bar2/bar3 are being sent back. 由于发送了bar1 / bar2 / bar3数组,因此增加了另一层复杂性。

Ex: 例如:

//Issue: is the second param bar1 bar2 or bar3?
//I put a questionmark where the issues occur, due to the fact 
//that I wouldn't know on the recieving side whether I'm going 
//to recieve bar1/bar2/bar3
? test = gson.fromJson(gsonString, ?);

I tried storing the type in foo, but without being able to parse it back there is no way to know the type. 我尝试将类型存储在foo中,但是无法将其解析回去,所以无法知道类型。

If you store the type in Foo like this: 如果您将类型存储在Foo中,如下所示:

private String fqcn; 

The you could do first a string search on the json string when receiving, to extract the fully qualified classname. 您可以在接收时首先对json字符串进行字符串搜索,以提取完全合格的类名。 Then you can use: 然后,您可以使用:

Foo test = gson.fromJson(gsonString, Class.forName( foundFqcn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM