利用Jackson封装常用JsonUtil工具类

在日常的项目开发中,接口与接口之间、前后端之间的数据传输一般都是使用JSON格式,那必然会封装一些常用的Json数据转化的工具类,本文讲解下如何利用Jackson封装高复用性的Json转换工具类。

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * jsonUtil工具类
 *
 * @author ryz
 * @since 2020-05-11
 */
public class JsonUtil {

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

    private static ObjectMapper mapper = new ObjectMapper();


    /**
     * 对象转Json格式字符串
     * @param obj 对象
     * @return Json格式字符串
     */
    public static <T> String obj2String(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Parse Object to String error : {}", e.getMessage());
            return null;
        }
    }

    /**
     * 对象转Json格式字符串(格式化的Json字符串)
     * @param obj 对象
     * @return 美化的Json格式字符串
     */
    public static <T> String obj2StringPretty(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Parse Object to String error : {}", e.getMessage());
            return null;
        }
    }

    /**
     * 字符串转换为自定义对象
     * @param str 要转换的字符串
     * @param clazz 自定义对象的class对象
     * @return 自定义对象
     */
    public static <T> T jsonToObj(String str, Class<T> clazz){
        if(StringUtil.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) str : mapper.readValue(str, clazz);
        } catch (Exception e) {
            LOGGER.warn("Parse String to Object error : {}", e.getMessage());
            return null;
        }
    }


    /**
     * 集合对象与Json字符串之间的转换
     * @param str 要转换的字符串
     * @param typeReference 集合类型如List<Object>
     * @param <T> 
     * @return
     */
    public static <T> T jsonToObj(String str, TypeReference<T> typeReference) {
        if (StringUtil.isEmpty(str) || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? str : mapper.readValue(str, typeReference));
        } catch (IOException e) {
            LOGGER.warn("Parse String to Object error", e);
            return null;
        }
    }

    /**
     * 集合对象与Json字符串之间的转换
     * @param str 要转换的字符串
     * @param collectionClazz 集合类型
     * @param elementClazzes 自定义对象的class对象
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzes) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
        try {
            return mapper.readValue(str, javaType);
        } catch (IOException e) {
            LOGGER.warn("Parse String to Object error : {}" + e.getMessage());
            return null;
        }
    }
}

User对象类

/**
 * 功能描述
 *
 * @since 2020-05-11
 */
public class User {
    private Integer id;
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

测试类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;

public class JsonUtilTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtilTest.class);

    public static void main(String[] args) {
        User user1 = new User();
        user1.setId(1);
        user1.setEmail("xxx@163.com");
        String userJsonstr = JsonUtil.obj2String(user1);
        String userJsonPretty = JsonUtil.obj2StringPretty(user1);
        LOGGER.info("userJson: {}", userJsonPretty);

        User user2 = JsonUtil.string2Obj(userJsonstr, User.class);
        user2.setId(2);
        user2.setEmail("xxx@126.com");

        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        String userListJson = JsonUtil.obj2String(userList);
        List<User> userListBean = JsonUtil.string2Obj(userListJson, new TypeReference<List<User>>() {});
        if (userListBean != null) {
            userListBean.forEach(user -> {
                System.out.println(user.getId() + " : " + user.getEmail());
            });
        }
        List<User> userListBean2 = JsonUtil.string2Obj(userListJson, List.class, User.class);
        if (userListBean2 != null) {
            userListBean2.forEach(user -> {
                System.out.println(user.getId() + " : " + user.getEmail());
            });
        }
    }
}

运行结果
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
hutool工具常用类包括类型转换工具类(Convert)、字符串工具类(StrUtil / StringUtils)、日期工具类(DateUtil)、数字工具类(NumberUtil)、数组工具类(ArrayUtil)、随机工具类(RandomUtil)、比较器工具类(ComparatorUtil)、多线程工具类(ThreadUtil)、IO流工具类(FileUtil)、集合工具类(CollUtil / CollectionsUtils)、正则工具类(ReUtil)、网络工具类(NetUtil)、JSON工具类JSONUtil)、系统信息工具类(SystemUtil)等等。这些工具类提供了一系列常用方法和功能,能够帮助开发者更加方便地进行类型转换、字符串处理、日期操作、数字处理、数组操作、随机数生、多线程管理、IO流操作、集合操作、正则表达式匹配、网络操作、JSON处理、系统信息获取等等。通过使用hutool工具类,开发者可以提高开发效率,减少代码量,提供更加稳定和高效的程序功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Hutool常用工具类](https://blog.csdn.net/abst122/article/details/124091375)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [hutool 工具类](https://download.csdn.net/download/LiHaoYang11/12153632)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [常用工具类 (三) : Hutool 常用工具类整理 (全)](https://blog.csdn.net/m0_37989980/article/details/126401041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值