对T的通用响应饰演Json [英] Generic ResponseTo<T> as Json

查看:89
本文介绍了对T的通用响应饰演Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力反序列化由通用结果结构包装的 JSON 对象:

I am struggling with deserialising a JSON object wrapped by a generic result structure:

我的 JSON :

{
  "totalsize": 5,
  "data" : [
             {"name":1},
             {"name":2}
           ]
}

结果中的

我的 Java 对象:

public class ResponseTo<T> {

    public Long totalsize = null;
    public final List<T> data = new ArrayList<>();
}

在这种情况下(可能是另一个GET请求中的其他内容)

And in this case (could be anything else on another GET request)

public class Item {
    public int name;
}

在这种情况下, T Item .

如何使用以下方法将 JSON 有效负载反序列化到此对象结构中:
GSON 和/或 com.fasterxml.jackson ?

How to deserialise a JSON payload into this object structure with:
GSON and/or com.fasterxml.jackson?

我想要一个静态方法,例如:

I want to have a static method like:

public static <T> ResponseTo<T> stringToObject(String jsonString, Class<T> clazz ) {
    final Gson gson = new Gson();
    // do some typeadapter function magic
    return gson.fromJson( jsonString, ResponseTo.class );
}

ResponseTo<Item> responseTo = stringToObject( <json-string>, Item.class );

我只收到 com.google.gson.internal.LinkedTreeMap 作为数据对象.

I only receive com.google.gson.internal.LinkedTreeMap as data objects.

我该怎么做才能使其正常工作?-我做错了吗?

What can I do to make it work? - Am I on a wrong way of doing it?

推荐答案

您需要使用类型令牌来处理一般情况,因为Java编译器将删除 T 的类型信息而且Gson不知道将 T 还原为哪种类型.

You need to use a type-token to handle generic cases, because the type information for T will be erased by the Java compiler and Gson wouldn't know what type to restore T to.

Type typeToken = new TypeToken<ResponseTo<Item>>() { }.getType();
ResponseTo<Item> responseTo = stringToObject( <json-string>, typeToken );

这篇关于对T的通用响应饰演Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆