使用Gson和接口类型

时间:2013-05-06 10:36:03

标签: java json gson

我正在研究一些服务器代码,客户端以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"
}

重申一下,我正在寻找一种方法来解析客户端的请求(In JSON)并返回实现Request接口的类的对象

6 个答案:

答案 0 :(得分:26)

如果没有某种程度的自定义编码,Gson中没有所描述类型的多态映射。有一个可用的扩展类型适配器as an extra提供了您正在寻找的大部分功能,需要注意的是多态子类型需要提前向适配器声明。以下是其使用示例:

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对象上定义type属性 - 它仅存在于JSON中。

答案 1 :(得分:9)

假设您可能拥有的不同可能的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
}

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

这样,您只需使用Request类解析许多不同的JSON响应,如下所示:

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

将JSON请求解析到您的类后,您可以将数据从 wrap 类传输到具体的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请求并且这些请求彼此非常不同,这种方法会变得有点繁琐,但即便如此,我认为这是一种很好且非常简单的方法......

答案 2 :(得分:4)

Genson库默认提供对多态类型的支持。以下是它的工作原理:

// tell genson to enable polymorphic types support
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();

// json value will be {"@class":"mypackage.LoginRequest", ... other properties ...}
String json = genson.serialize(someRequest);
// the value of @class property will be used to detect that the concrete type is LoginRequest
Request request = genson.deserialize(json, Request.class);

您还可以为类型使用别名。

// a better way to achieve the same thing would be to use an alias
// no need to use setWithClassMetadata(true) as when you add an alias Genson 
// will automatically enable the class metadata mechanism
genson = new Genson.Builder().addAlias("loginRequest", LoginRequest.class).create();

// output is {"@class":"loginRequest", ... other properties ...}
genson.serialize(someRequest);

答案 3 :(得分:0)

默认情况下,GSON无法区分序列化为JSON的类;换句话说,你需要明确地告诉解析器你期望什么类。

解决方案可以自定义反序列化或使用类型适配器,如here所述。

答案 4 :(得分:0)

我找到了这个答案:https://stackoverflow.com/a/28830173解决了使用日历作为接口的问题,因为RunTimeType将是GregorianCalendar。

答案 5 :(得分:0)

具有用于为通用类型的接口创建GSON的实用程序方法。

//用于注册接口的实用程序方法及其与GSON配合使用的实现

public static <T> Gson buildInterface(Class<T> interfaceType, List<Class<? extends T>> interfaceImplmentations) {
    final RuntimeTypeAdapterFactory<T> typeFactory = RuntimeTypeAdapterFactory.of(interfaceType, "type");
    for (Class<? extends T> implementation : interfaceImplmentations) {
        typeFactory.registerSubtype(implementation);
    }
    final Gson gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();
    return gson;
}

//构建Gson

List<Class<? extends Request>> customConfigs = new ArrayList<>();
customConfigs.add(LoginRequest.getClass());
customConfigs.add(SomeOtherRequest.getClass());
Gson gson = buildInterface(Request.class, customConfigs);

使用此gson进行序列化或反序列化即可。