I am working on some server code, where the client sends requests in form of JSON. My problem is, there are a number of possible requests, all varying in small implementation details. I therefore thought to use a Request interface, defined as:
public interface Request {
Response process ( );
}
From there, I implemented the interface in a class named LoginRequest
as shown:
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 + "]";
}
}
To work with JSON, I created a GsonBuilder
instance and registered an InstanceCreator
as shown:
public class LoginRequestCreator implements InstanceCreator<LoginRequest> {
@Override
public LoginRequest createInstance(Type arg0) {
return new LoginRequest("username", "password");
}
}
which I then used as shown in the snippet below:
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);
and I get the expected output.
The thing I wish to do is replace the line Request request = parser.fromJson(completeInput, LoginRequest.class);
with something similar to Request request = parser.fromJson(completeInput, Request.class);
but doing that will not work, since Request
is an interface.
I want my Gson
to return the appropriate type of request depending on the received JSON.
An example of the JSON I passed to the server is shown below:
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
To reiterate, I am looking for a way to parse requests (In JSON) from clients and return objects of classes implementing the Request
interface