java工具类-jackson

使用场景:
工作中,接口与接口交互时,常常会将json和bean/list相互转化,来处理。本文基于jackson来封装工具

浩瀚的网络中,你我的相遇也是种缘分,看你天资聪慧、骨骼精奇,就送你一场大造化吧,能领悟多少就看你自己了。㊙传承之地🙇

1.说明

如果没使用springboot的话,那么需要添加依赖,并初始化对象

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.4</version>
</dependency>

如何在springboot中使用的,不用添加依赖,也可以不用自己实例化,使用spring容器已实例化的objectMapper,只要将对象交给容器管理,并注入对应的实列即可。
(当然了不用ioc容器的,自己创建一个实列也无可厚非)

2.工具类

主要以下几个方法

  • json转对象
  • 对象转json(json格式化)
  • json转化为泛型类型对象(集合等泛型方式)
package com.iworkh.test.restassured.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * json转化工具类
 *
 * @author: iworkh-沐雨云楼
 * @date: 2020-06-18
 */
public class JacksonTool {

    private static final Logger LOGGER = LoggerFactory.getLogger(JacksonTool.class);

    private final static ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
        // 忽略json中在对象不存在对应属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略空bean转json错误
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }

    /**
     * json转对象
     *
     * @param jsonStr   json串
     * @param classType 对象类型
     * @return 对象
     */
    public static <T> T toEntity(String jsonStr, Class<T> classType) {

        if (StringUtils.isEmpty(jsonStr)) {
            LOGGER.warn("Json string {} is empty!", classType);
            return null;
        }

        try {
            return mapper.readValue(jsonStr, classType);
        } catch (IOException e) {
            LOGGER.error("json to entity error.", e);
        }
        return null;
    }

    /**
     * json转化为带泛型的对象
     *
     * @param jsonStr json字符串
     * @param typeReference 转化类型
     * @return 对象
     */
    public static <T> T toEntity(String jsonStr, TypeReference<T> typeReference) {
        if (StringUtils.isBlank(jsonStr) || typeReference == null) {
            return null;
        }
        try {
            return (T) mapper.readValue(jsonStr, typeReference);
        } catch (JsonProcessingException e) {
            LOGGER.error("json to entity error.", e);
        }
        return null;
    }

    /**
     * 对象转json
     *
     * @param obj 对象
     * @return json串
     */
    public static String toJson(Object obj) {
        if (obj instanceof String) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (IOException e) {
            LOGGER.error("obj to json error.", e);
        }
        return null;
    }

    /**
     * 对象转json(格式化的json)
     *
     * @param obj 对象
     * @return 格式化的json串
     */
    public static String toJsonWithFormat(Object obj) {
        if (obj == null) {
            return null;
        }

        if (obj instanceof String) {
            return (String) obj;
        }

        try {
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (IOException e) {
            LOGGER.error("obj to json error.", e);
        }
        return null;
    }
}

3.调用

使用很简单,主要注意下泛型对象的转化使用 new TypeReference<List<UserVo>>() {})

public class JacksonToolTest {

    @Test
    public void testEntityToJson() {
        String[] hobbies = {"football", "sing"};
        UserVo user = new UserVo(1, "iworkh", System.currentTimeMillis(), false, Arrays.asList(hobbies));
        String json = JacksonTool.toJson(user);
        System.out.println(json);
    }

    @Test
    public void testJsonToEntity() {
        String json = "{\"id\":1,\"name\":\"iworkh\",\"birthday\":1592575139578,\"vip\":false,\"hobbies\":[\"football\",\"sing\"]}";
        UserVo userVo = JacksonTool.toEntity(json, UserVo.class);
        if (userVo != null) {
            System.out.println(userVo.getName());
        }
    }


    @Test
    public void testListEntityToJson() {
        String[] hobbies = {"football", "sing"};
        UserVo user1 = new UserVo(1, "iworkh1", System.currentTimeMillis(), false, Arrays.asList(hobbies));
        UserVo user2 = new UserVo(2, "iworkh2", System.currentTimeMillis(), false, Arrays.asList(hobbies));
        ArrayList<UserVo> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        String json = JacksonTool.toJson(list);
        System.out.println(json);
    }

    @Test
    public void testJsonToListEntity() {
        String json = "[{\"id\":1,\"name\":\"iworkh1\",\"birthday\":1592575376189,\"vip\":false,\"hobbies\":[\"football\",\"sing\"]}," + "{\"id\":2,\"name\":\"iworkh2\",\"birthday\":1592575376189,\"vip\":false,\"hobbies\":[\"football\",\"sing\"]}]";
        List<UserVo> userList = JacksonTool.toEntity(json, new TypeReference<List<UserVo>>() {
        });

        userList.forEach(item -> {
            System.out.println(item.getName());
        });
    }
}

4.推荐

能读到文章最后,首先得谢谢您对本文的肯定,你的肯定是对我们的最大鼓励。

你觉本文有帮助,那就点个👍
你有疑问,那就留下您的💬
怕把我弄丢了,那就把我⭐
电脑不方便看,那就把发到你📲

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值