java json 泛型_抽象泛型类中,json转换类型丢失解决办法

在 抽象泛型类中,一般会自动将数据转换操作实现,使用者就不用关心数据转换过程,专注业务处理就行了

重新实现TypeReference类中_type获取的实现,这里是基于jackson的实现示例,JsonUtil工具类是对jackson的实现,这里就不提供了,其他json转换实现方法类似

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

import com.bc.core.util.JsonUtil;

import com.fasterxml.jackson.core.type.TypeReference;

public abstract class BaseTopicMsgHandle {

public abstract String topic();

public abstract void handle(T data);

public void jsonHandle(String json) {

T obj = toObject(json);

if (obj == null) {

return;

}

handle(obj);

}

protected TypeReferenceT typeReferenceT = new TypeReferenceT();

public T toObject(String json) {

return JsonUtil.toObject(json, typeReferenceT);

}

private class TypeReferenceT extends TypeReference {

protected final Type _type;

TypeReferenceT() {

Type superClass = BaseTopicMsgHandle.this.getClass().getGenericSuperclass();

if (superClass instanceof Class>) {

throw new IllegalArgumentException(

"Internal error: TypeReference constructed without actual type information");

}

_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];

}

@Override

public Type getType() {

return _type;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值