[英]Convert JSON data to Java object (including the Object class) using GSON
Let's suppose to receive the following JSON data: 让我们假设接收以下JSON数据:
{
"request" : "connection_status",
"data" : { "id" : "foo", "username" : "bar" }
}
and you want to deserialize that to a Java object whose class is defined like this: 并且您想将其反序列化为其类定义如下的Java对象:
public class SingleJsonObjectRequest {
private String request;
private Object data;
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
Clearly, you even have the following class: 显然,您甚至拥有以下课程:
public class UserInfo {
private String id;
private String username;
public String getId() {
return id;
}
public UserInfo setId(String id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserInfo setUsername(String username) {
this.username = username;
return this;
}
}
which can be included into SingleJsonObjectRequest by calling: 可以通过调用将其包含在SingleJsonObjectRequest中:
singleObjReq.setData(new UserInfo());
Is there any way to convert that JSON data to a SingleJsonObjectRequest object? 有什么方法可以将JSON数据转换为SingleJsonObjectRequest对象? I mean, you cannot use the following code:
我的意思是,您不能使用以下代码:
SingleJsonObjectRequest singleObjReq = gson.fromJson(jsonReq, SingleJsonObjectRequest.class);
because SingleJsonObjectRequest has a general data Object, not a UserInfo object. 因为SingleJsonObjectRequest具有常规数据对象,而不是UserInfo对象。
You can write a custom deserializer ( https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer ). 您可以编写自定义反序列化器( https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer )。
IMHO, you have to use separate class for each data type you want to send/receive. 恕我直言,您必须为要发送/接收的每种数据类型使用单独的类。 You can create a generic base class like this
您可以像这样创建通用基类
class JsonRequest<T>{
private String request;
private T data;
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
and use subclasses for each type, because java doesnot store generic types information For example 并为每种类型使用子类,因为Java不存储泛型类型信息,例如
class UserInfoRequest extends JsonRequest<UserInfo>{
//nothing in here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.