java泛型 json序列化,使用GSON或Jackson将JSON反序列化为具有泛型参数的类

I'm getting responses from my server that look like:

{

"timestamp" : 1,

"some other data": "blah",

"result" : {

...

}

}

for a variety of calls. What I want to do client side is:

class ServerResponse {

long timestamp;

T result;

}

and then deserialize that with GSON or Jackson. I've been unable to do so thanks to type erasure. I've cheated that using subclasses like this:

class SpecificResponse extends ServerRequest {}

but that requires a bunch of useless classes to lie around. Anyone have a better way?

I also need to be able to handle the case of result being an array.

解决方案

The typical solution to type erasure in this case is the type token hack which takes advantage of anonymous classes maintaining superclass information for use with reflection.

Jackson provides the TypeReference type as well as an ObjectMapper#readValue overload to use it.

In your example, you'd use

ServerResponse response = objectMapper.readValue(theJsonSource, new TypeReference>() {});

Note that this is not type-safe so you must be careful that the type you try to assign to is compatible with the generic type argument you used in the anonymous class instance creation expression.

As for supporting both single values and arrays in the JSON, you can change your field to be of some Collection type. For example,

List results

Feature that determines whether it is acceptable to coerce non-array

(in JSON) values to work with Java collection (arrays,

java.util.Collection) types. If enabled, collection deserializers will

try to handle non-array values as if they had "implicit" surrounding

JSON array.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用fastjson进行泛型反序列化,你可以按照以下步骤进行操作: 首先,确保你已经引入了fastjson的依赖,可以通过Maven等构建工具添加以下依赖项: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.79</version> </dependency> ``` 接下来,假设你有一个泛型`Result<T>`,如下所示: ```java import com.alibaba.fastjson.JSON; public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } public static <T> Result<T> fromJson(String json, Class<T> clazz) { return JSON.parseObject(json, new TypeReference<Result<T>>(clazz) {}.getType()); } } ``` 在上述代码中,`fromJSON`方法使用fastjson的`parseObject`方法将JSON字符串反序列化为`Result<T>`对象。 然后,你可以使用以下代码将JSON字符串反序列化为具体的泛型对象: ```java import com.alibaba.fastjson.JSON; public class Main { public static void main(String[] args) { String json = "{\"code\":200,\"message\":\"Success\",\"data\":{\"name\":\"John\",\"age\":25}}"; Result<User> result = Result.fromJson(json, User.class); System.out.println("Code: " + result.getCode()); System.out.println("Message: " + result.getMessage()); User user = result.getData(); System.out.println("Name: " + user.getName()); System.out.println("Age: " + user.getAge()); } } ``` 在上述代码中,我们将一个包含`User`对象的JSON字符串反序列化为`Result<User>`对象,并输出其中的字段值。 请注意,为了正确反序列化泛型,我们需要通过传递`Class<T>`参数给`fromJSON`方法来指定具体的泛型型。 以上就是使用fastjson进行泛型反序列化的基本示例。当然,根据实际需求和数据结构的复杂程度,你可能需要进行更多的定制和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值