클라이언트가 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 request = parser.fromJson(completeInput, LoginRequest.class);
을 Request request = parser.fromJson(completeInput, Request.class);
과 비슷한 것으로 바꾸는 것이 효과가 없습니다.
내 Gson
에 수신 된 JSON에 따라 적절한 유형의 요청을 반환하고 싶습니다.
내가 서버에 전달 된 JSON의 예는 다음과 같습니다
{
"type":"LOGIN",
"username":"someuser",
"password":"somepass"
}
가 반복하기 위해, 나는를 구현하는 클래스의 객체를 클라이언트에서 (JSON에서) 요청을 구문 분석하고 반환 할 수있는 방법을 찾고 있어요 Request
인터페이스
서버에서 얻을 수있는 다양한 JSON 응답의 다른 예를 제공해 주실 수 있습니까? 왜냐하면 당신이 많은 가능성과 아주 다른 가능성을 가지고 있지 않다면, 당신이 쉽게 할 수있는 일이 있기 때문입니다 ... – MikO
당신의 의견을 위해 @MiKO를 고맙게 생각합니다. 다른 가능성있는 요청은'PlayRequest','LogoutRequest','GetPlayersRequest','JoinGameRequest','StartGameRequest' 등입니다 ... – fredmanglis
적어도 다른 유형의 요청에 대한 JSON 요청의 예제를 제공 할 수 있다면 . 내'LoginRequest'에 대해서'type','username','password' 등 다른 요청은 어떻게 되나요? 어떻게 보이나요? – MikO