将 Gson 与接口类型结合使用

2022-09-01 14:22:32

我正在处理一些服务器代码,其中客户端以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,我创建了一个实例并注册了一个实例,如下所示:GsonBuilderInstanceCreator

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


答案 1

如果没有一定程度的自定义编码,所描述的类型的多态映射在Gson中不可用。有一个扩展类型适配器作为附加功能提供,它提供了您要查找的大部分功能,但需要注意的是,多态子类型需要提前向适配器声明。以下是其用法示例:

public interface Response {}

public interface Request {
    public Response process();
}

public class LoginRequest implements Request {
    private String userName;
    private String password;

    // Constructors, getters/setters, overrides
}

public class PingRequest implements Request {
    private String host;
    private Integer attempts;

    // Constructors, getters/setters, overrides
}

public class RequestTest {

    @Test
    public void testPolymorphicSerializeDeserializeWithGSON() throws Exception {
        final TypeToken<List<Request>> requestListTypeToken = new TypeToken<List<Request>>() {
        };

        final RuntimeTypeAdapterFactory<Request> typeFactory = RuntimeTypeAdapterFactory
                .of(Request.class, "type")
                .registerSubtype(LoginRequest.class)
                .registerSubtype(PingRequest.class);

        final Gson gson = new GsonBuilder().registerTypeAdapterFactory(
                typeFactory).create();

        final List<Request> requestList = Arrays.asList(new LoginRequest(
                "bob.villa", "passw0rd"), new LoginRequest("nantucket.jones",
                "crabdip"), new PingRequest("example.com", 5));

        final String serialized = gson.toJson(requestList,
                requestListTypeToken.getType());
        System.out.println("Original List: " + requestList);
        System.out.println("Serialized JSON: " + serialized);

        final List<Request> deserializedRequestList = gson.fromJson(serialized,
                requestListTypeToken.getType());

        System.out.println("Deserialized list: " + deserializedRequestList);
    }
}

请注意,您实际上不需要在单个 Java 对象上定义属性 - 它仅存在于 JSON 中。type


答案 2

假设您可能拥有的不同可能的JSON请求彼此之间没有太大的不同,我建议使用一种不同的方法,在我看来更简单。

假设您有以下 3 个不同的 JSON 请求:

{
    "type":"LOGIN",
    "username":"someuser",
    "password":"somepass"
}
////////////////////////////////
{
    "type":"SOMEREQUEST",
    "param1":"someValue",
    "param2":"someValue"
}
////////////////////////////////
{
    "type":"OTHERREQUEST",
    "param3":"someValue"
}

Gson允许您使用单个类来包装所有可能的响应,如下所示:

public class Request { 
  @SerializedName("type")   
  private String type;
  @SerializedName("username")
  private String username;
  @SerializedName("password")
  private String password;
  @SerializedName("param1")
  private String param1;
  @SerializedName("param2")
  private String param2;
  @SerializedName("param3")
  private String param3;
  //getters & setters
}

通过使用注释,当Gson尝试解析JSON请求时,它只需查找类中的每个命名属性中是否存在具有相同名称的字段。如果没有这样的字段,则类中的属性仅设置为 。@SerializedNamenull

通过这种方式,您可以仅使用您的类来解析许多不同的 JSON 响应,如下所示:Request

Gson gson = new Gson();
Request request = gson.fromJson(jsonString, Request.class);

将 JSON 请求解析到类中后,可以将数据从包装类传输到具体对象,如下所示:XxxxRequest

switch (request.getType()) {
  case "LOGIN":
    LoginRequest req = new LoginRequest(request.getUsername(), request.getPassword());
    break;
  case "SOMEREQUEST":
    SomeRequest req = new SomeRequest(request.getParam1(), request.getParam2());
    break;
  case "OTHERREQUEST":
    OtherRequest req = new OtherRequest(request.getParam3());
    break;
}

请注意,如果您有许多不同的JSON请求并且这些请求彼此非常不同,则此方法会变得更加乏味,但即使如此,我认为这是一种很好且非常简单的方法...