Jackson家庭成员之TypeReference

Jackson简介

Jackson是一个简单的、功能强大的、基于Java的应用库。它可以实现Java对象和Json对象/XML文档之间的互转。它也是spring家族默认的JSON/XML解析器。

相关网站链接:

  1. fasterxml官网
  2. jackson的github链接
  3. jackson通用漏洞报告
  4. 成为一个偷懒且高效的安卓开发人员——部分3:JSON解析库

pom中的依赖如下,

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.core.version}</version>
</dependency>

TypeReference

TypeReference是jackson的核心成员,它能够支持对泛型对象的反序列化。

package com.hust.zhang.generic;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TypeReferenceDemo {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @Data
    private static class Demo {
        private String name;

        private int age;
    }

    public static void main(String[] args) {
        // 泛型的反序列化
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
        List<String> stringList = getResponse(JSON.toJSONString(list), null, new TypeReference<List<String>>() {
        });
        String test = "{\"age\":1,\"name\":\"zhangsan\"}";
        Demo testObj1 = getResponse(test, Demo.class, null);
        Demo testObj2 = getResponse(test, null, new TypeReference<Demo>() {
        });
        System.out.println(stringList);
        System.out.println(JSON.toJSONString(testObj1));
        System.out.println(JSON.toJSONString(testObj2));
    }

    private static <T> T getResponse(String request, Class<T> clazz, TypeReference<T> typeReference) {
        T result;
        if (clazz != null) {
            result = unMarshal(request, clazz);
        } else {
            result = unMarshal(request, typeReference);
        }
        return result;
    }

    private static <T> T unMarshal(String request, Class<T> clazz) {
        try {
            return objectMapper.readValue(request, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static <T> T unMarshal(String request, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(request, typeReference);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

以上面示例为例,列表可以通过TypeReference传入泛型对象进行反序列化。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值