gson 将JSON字符串反序列化为 Package 泛型类的类

bhmjp9jg  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(181)

先说一下背景。
我有一个 Package 类:

public class ResponseEntity<T> {
    private String code;
    private String message;
    private T data;

    public ResponseEntity(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public ResponseEntity(String code, String message) {
        this.code = code;
        this.message = message;
        this.data = null;
    }

  ...getters...
}

然后我有我在里面使用的类:

public class Foo {
    private String name;
    private String age;

    public Foo(String name, String age) {
        this.name = name;
        this.age = age;
    }
    ...getters...
}

我使用AWS Lambda,因此ResponseEntity在AWS Lambda响应类内的body字段中序列化:some-lambda-handler-class.java

public APIGatewayProxyResponseEvent handleRequest(String name, String age) {
  Foo foo = new Foo(name, age);
  ResponseEntity<Foo> fooResponse = new ResponseEntity("code", "msg", foo);
  String body = gson.toJson(fooResponse);
  APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
  response.setBody(body);
  return response;
}

问题是当我测试我的处理程序类时:some-lambda-handler-class-test.java

@Test
public void test() {
    APIGatewayProxyResponseEvent response = myHandler.handleRequest("foo", "bar");
    ResponseEntity<Foo> fooResponse = gson.fromJson(response.getBody(), ResponseEntity.class);

    assertThat(fooResponse.getCode(), is("code")); // This assert is Ok
    assertThat(fooResponse.getMessage(), is("msg")); // This assert is Ok
    assertThat(fooResponse.getData().getName(), is("foo")); // this throws an error 
// Error is: java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class Foo (com.google.gson.internal.LinkedTreeMap and Foo are in unnamed module of loader 'app')
    assertThat(fooResponse.getData().getAge(), is("bar"));
}

我从这个错误中了解到,我必须以某种方式告诉gson,我想从json反序列化的类是ResponseEntity<Foo>.class,所以不要使用LinkedTreeMap作为data字段,而要使用Foo
但我不知道怎么做。因为如果我做了:

ResponseEntity<Foo> fooResponse = gson.fromJson(response.getBody(), ResponseEntity<Foo>.class);
// The "ResponseEntity<Foo>.class" part shows an error ("Cannot select from parameterized type")

所以问题是

如何让Gson将JSON字符串反序列化为ResponseEntity<Foo>类?

先谢谢你。

lvjbypge

lvjbypge1#

您必须使用

gson.fromJson(response.getBody(), new TypeToken<ResponseEntity<Foo>>() {}.getType());

因为您使用了 Package 类

ResponseEntity<Foo>.class

不可能,因为.class忽略〈〉参数

相关问题