常用的三个反序列化:JavaType、MapType、CollectionType的运用

本文介绍了JavaType、MapType和CollectionType在反序列化过程中的关系和使用。MapType和CollectionType继承自JavaType,并实现了JsonSerializable接口。通过示例代码展示了如何在实际操作中运用这三个类型进行JSON实例化。

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

首先要了解他们之间的关系
当我们跟踪MapType能看到;MapType->MapLikeType->TypeBase->JavaType然后实现json实例化接口JsonSerializable
当我们跟踪CollectionType能看到:CollectionType->CollectionLikeType->TypeBase->JavaType然后实现json实例化接口JsonSerializable
从这可以看出MapType、CollectionType都是JavaType的子类。其实可以看看JavaType的结构图就能很清晰的看到JavaType有哪些子类,这里我就不展示了。
接下来我们就来代码展示:
1.创建一个实体类:PerSon

@Data
public class PerSon{
    String name;
    int age;
    }

2.TestJavaType

public class TestJavaType {
  public static void main(String[] args) {
    PerSon perSon=new PerSon();
        perSon.setName("xiaofu");
        perSon.setAge(22);
        //将PerSon类实例化为String
        String persons=JsonMapper.getInstance().writeValueAsString(perSon);
        System.out.println(persons);
        //定义反序列化的类型
        JavaType javaType=TypeFactory.defaultInstance().constructType(PerSon.class);
        //根据定义类型进行转化
        PerSon personJavaType=JsonMapper.getInstance().readValue(persons,javaType);
        System.out.println(personJavaType);
        }
    }

3.TestMapType

public class TestMapType {
  public static void main(String[] args) {
    PerSon perSon=new PerSon();
        perSon.setName("xiaofu");
        perSon.setAge(22);
        //创建map对象
    Map<Integer,PerSon> map=new HashedMap<>();
        map.put(1,perSon);
        //实例化为String
    String personmap=JsonMapper.getInstance().writeValueAsString(map);
        System.out.println(personmap);
         //定义反序列化的类型
    MapType mapType=TypeFactory.defaultInstance().constructMapType(Map.class,Integer.class,PerSon.class);
     //根据定义类型进行转化
    Map<Integer,PerSon> integerPerSonMap=JsonMapper.getInstance().readValue(personmap,mapType);
        System.out.println(integerPerSonMap);
        }
        }

4.TestListType

public class TestListType {
    public static void main(String[] args) {
        PerSon perSon=new PerSon();
        perSon.setName("xiaofu");
        perSon.setAge(22);
        //创建List
        List<PerSon> perSonList=new ArrayList<>();
        perSonList.add(perSon);
        //实例化为String
        String personList=JsonMapper.getInstance().writeValueAsString(perSonList);
        System.out.println(personList);
        //定义反序列化的类型
        CollectionType collections = TypeFactory.defaultInstance().constructType(List.class,Person.class);
         //根据定义类型进行转化
        List<PerSon> perSonList1=JsonMapper.getInstance().readValue(personList,collections);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值