[英]Using Gson How to convert Json object that contains object of an interface that implemented by many classes - Java
I have an object of UserMsg
that I want to send using JSON
我有一个要使用
JSON
发送的UserMsg
对象
public class UserMsg {
private String Type;
private UserData userData;
//Getters & Setters }
UserData
is an Interface UserData
是一个接口
there are many classes implementing UserData
.. and everytime I send the Json Object Its userData
could be an object of any of these classes. 有许多实现
UserData
类。每当我发送Json对象时,它的userData
可能是任何这些类的对象。
so on the Receiving side I used this code: 因此在接收端,我使用了以下代码:
Gson gson = new Gson();
UserMsg usermsg = gson.fromJson(JsonObject,UserMsg.class);
and got this error: 并得到此错误:
Unable to invoke no-args constructor for interface UserData.
无法为接口UserData调用no-args构造函数。 Register an InstanceCreator with Gson for this type may fix this problem.
使用此类型向Gson注册InstanceCreator可能会解决此问题。
I tried to Register an InstanceCreator
for UserData
but It doesn't work so I need the right way to make it run. 我尝试为
UserData
注册InstanceCreator
,但是它不起作用,因此我需要正确的方法来使其运行。
You may want to create a custom Adapter and inside the read/write methods you may set the parsing methodology in order to handle different classes implementing your UserData
interface. 您可能要创建一个自定义适配器,并在读/写方法内部设置解析方法,以便处理实现
UserData
接口的不同类。 Something like this: 像这样:
public class UserMsgAdapter extends TypeAdapter {
@Override
public UserMsg read(final JsonReader in) throws IOException {
final UserMsg data = new UserMsg();
in.beginObject();
while (in.hasNext()) {
in.nextName();
if(in.nextString().equals(someType))
// create one instance of a particular implementation
}
}
in.endObject();
return data;
}
@Override
public void write(final JsonWriter out, final UserMsg msg) throws IOException {
out.beginObject();
// write according to the instance type
out.endObject();
}
}
And dont forget to register this custom adapter: 并且不要忘记注册此自定义适配器:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(UserMsg.class, new UserMsgAdapter());
final Gson gson = gsonBuilder.create();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.