将 Gson 与接口类型结合使用
我正在处理一些服务器代码,其中客户端以JSON的形式发送请求。我的问题是,有许多可能的请求,所有这些请求都因小的实现细节而异。因此,我想使用请求接口,定义为:
public interface Request {
Response process ( );
}
从那里,我在一个名为如下所示的类中实现了该接口:LoginRequest
public class LoginRequest implements Request {
private String type = "LOGIN";
private String username;
private String password;
public LoginRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* This method is what actually runs the login process, returning an
* appropriate response depending on the outcome of the process.
*/
@Override
public Response process() {
// TODO: Authenticate the user - Does username/password combo exist
// TODO: If the user details are ok, create the Player and add to list of available players
// TODO: Return a response indicating success or failure of the authentication
return null;
}
@Override
public String toString() {
return "LoginRequest [type=" + type + ", username=" + username
+ ", password=" + password + "]";
}
}
为了使用 JSON,我创建了一个实例并注册了一个实例,如下所示:GsonBuilder
InstanceCreator
public class LoginRequestCreator implements InstanceCreator<LoginRequest> {
@Override
public LoginRequest createInstance(Type arg0) {
return new LoginRequest("username", "password");
}
}
然后我使用了它,如下面的代码片段所示:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(LoginRequest.class, new LoginRequestCreator());
Gson parser = builder.create();
Request request = parser.fromJson(completeInput, LoginRequest.class);
System.out.println(request);
我得到了预期的输出。
我想做的是用类似的东西替换行,但这样做是行不通的,因为它是一个接口。Request request = parser.fromJson(completeInput, LoginRequest.class);
Request request = parser.fromJson(completeInput, Request.class);
Request
我希望根据收到的 JSON 返回适当类型的请求。Gson
我传递给服务器的 JSON 示例如下所示:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
重申一下,我正在寻找一种方法来解析来自客户端的请求(在JSON中),并返回实现接口的类的对象。Request