我正在处理一些服务器代码,客户端以 JSON 的形式发送请求。我的问题是,有许多可能的请求,都在小的实现细节上有所不同。因此,我想使用一个 Request 接口,定义为:
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
它是一个接口。
我希望我Gson
根据收到的 JSON 返回适当类型的请求。
我传递给服务器的 JSON 示例如下所示:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
重申一下,我正在寻找一种方法来解析来自客户端的请求(在 JSON 中)并返回实现Request
接口的类的对象