使用Gson转json字符串序列化问题

本文介绍使用Gson进行JSON字符串序列化时遇到的问题及其解决办法,详细展示了如何通过自定义日期类型适配器来避免UnsupportedOperationException异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Gson转json字符串序列化问题
gson序列化会遇到问题:
java.lang.UnsupportedOperationException: Expecting parameterized type, got class

Are you missing the use of TypeToken idiom?

See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener

at com.google.gson.TypeInfoFactory.getActualType(TypeInfoFactory.java:105)

at com.google.gson.TypeInfoFactory.getTypeInfoForField(TypeInfoFactory.java:54)

at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:156)

at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:131)

at com.google.gson.JsonSerializationContextDefault.serialize(JsonSerializationContextDefault.java:56)

at com.google.gson.Gson.toJsonTree(Gson.java:233)

at com.google.gson.Gson.toJson(Gson.java:273)

at com.google.gson.Gson.toJson(Gson.java:253)

解决办法如下:
private static Gson gsonUtils = null;

public synchronized static Gson getGsonUtils(){
    if(gsonUtils == null) {
        GsonBuilder builder = new GsonBuilder()
            .registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
                @Override
                public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
                    return new JsonPrimitive(src.getTime());
                }
            }).registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    return new Date(json.getAsJsonPrimitive().getAsLong());
                }
            }).setDateFormat(DateFormat.LONG);
        gsonUtils = builder.create();
    }
    return gsonUtils;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值