jsckson序列化处理泛型

阅读更多
我有这样两个类

package com.vipshop.mapi.wallet.test;

import java.util.List;


public class A {

    private List list;

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }
}

package com.vipshop.mapi.wallet.test;


public class B {
    private String name = "test";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


我们注意到a类是有泛型的,内容是动态的,我们开始的想法是这样的,动态构建一个TypeReference就行了吗

    public static  TypeReference> getReference(T clz) {
        return new TypeReference>() {};
    }


但是实际上是不行的,TypeReference的类型是类型定义的时候就确定了的,和你传进去的没有关系的,永远是>

那我们要怎么做呢,
一种做法是覆盖TypeReference的getType方法,把真实的type动态构造传进去,就是方法getReference2

另外一种做法是利用jackson提供的构造JavaType的方式,就是方法getReference3



package com.vipshop.mapi.wallet.test;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cloud.huang on 17/1/10.
 */
public class JacksonTest {
    private static final ObjectMapper objectMapper = new ObjectMapper();



    public static void main(String[] args) throws Exception {
        List list = new ArrayList<>();
        list.add(new B());
        A a = new A();
        a.setList(list);

        String json = objectMapper.writeValueAsString(a);
        TypeReference typeReference = getReference2(B.class);
//        JavaType typeReference = getReference3(B.class);
        A a2 = objectMapper.readValue(json, typeReference);

    }


    public static TypeReference getReference2(Type clz) {
        Type[] types = new Type[1];
        types[0] = clz;
        final ParameterizedTypeImpl type = ParameterizedTypeImpl.make(A.class, types, A.class.getDeclaringClass());
        return new TypeReference() {
            @Override
            public Type getType() {
                return type;
            }
        };
    }


    public static JavaType getReference3(Class clz) {
        JavaType type = objectMapper.getTypeFactory().constructParametrizedType(A.class, A.class, clz);
        return type;
    }
}




当然有人说,我们其实只要写一个new TypeReference>()就可以了,但是如果我们想动态的传入B类型的话,还是有必要的。


你可能感兴趣的:(jsckson序列化处理泛型)