com.alibaba.fastjson.JSONException: parse enum AppType error, value : {"type":3}

使用@JSONType后,无法反序列化,需要自己写反序列化,比如:

package com.alibaba.json.bvt.serializer.enum_;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import junit.framework.TestCase;

import java.lang.reflect.Type;

public class EnumCustomCodecTest extends TestCase {

    public void test_for_enum() throws Exception {
        Type type = Type.A;
        String str =JSON.toJSONString(type);

        assertEquals("{\"id\":1001,\"name\":\"aaa\"}", str);

        Type type2 = JSON.parseObject(str, Type.class);
        Type type3 = JSON.parseObject(str, Type.class);

        assertSame(type, type2);
        assertSame(type, type3);

    }

    @JSONType(serializeEnumAsJavaBean = true, deserializer = TypeDeser.class)
    public static enum Type {
        A(1001, "aaa"), B(1002, "bbb")
        ;

        public int id;
        public String name;

        Type(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public static Type valueOf(long id) {
            if (id == 1001) {
                return A;
            } else if (id == 1002) {
                return B;
            }
            return null;
        }
    }

    public static class TypeDeser implements ObjectDeserializer {

        public <T> T deserialze(DefaultJSONParser parser, java.lang.reflect.Type type, Object fieldName) {
            JSONObject object = parser.parseObject();
            long id = object.getLongValue("id");
            return (T) Type.valueOf(id);
        }

        public int getFastMatchToken() {
            return 0;
        }
    }
}

参考链接:
enum使用@JSONType后,无法反序列化

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值