我正在處理一些服務器代碼,其中客戶端以JSON的形式發送請求。我的問題是,有很多可能的請求,所有請求都有所不同,這些請求在小的實現細節上有所不同 因此,我想用一個請求接口,定義爲:使用Gson與接口類型
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
接口
你能否提供其他的例子,你可以從服務器獲得不同的JSON響應?因爲如果你沒有很多不同的可能性,那麼你可以輕鬆地做... – MikO 2013-05-06 11:14:17
感謝@MiKO的輸入。其他可能的請求是「PlayRequest」,「LogoutRequest」,「GetPlayersRequest」,「JoinGameRequest」,「StartGameRequest」等... – fredmanglis 2013-05-06 12:26:32
我的意思是,如果您可以提供至少其中一種請求的JSON請求示例。我的意思是,對於你的'LoginRequest',你有類型:'type','username'和'password',那麼其他請求呢?他們看起來如何? – MikO 2013-05-06 12:49:51