JsonUtils

JsonUtils工具类

1、JSON字符串转换为对象
2、对象转换为JSON字符串
3、对象转换为JSON字符串(不忽略null)
4、对象之间转换
5、List 转化为 List<Map<String, Object>>
6、object 转化为 map
/*
 * Copyright (c) 2019.
 * hnf Co.Ltd. 2002-
 * All rights resolved
 */
package com.meiyuan.rights.sdk.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.meiyuan.rights.sdk.domain.vo.TokenParam;
import com.meiyuan.rights.sdk.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * JSON 操作工具类
 *
 * @author zj
 * @version v1.0.0
 * @date 2020/10/19 15:04
 */
@Slf4j
public class JsonUtils {

    /**
     * JSON字符串转换为对象
     *
     * @param json       JSON字符串
     * @param targetType 类型
     * @param <T>        泛型
     * @return 对象
     */
    public static <T> T jsonToObject(@NotNull String json, Class<T> targetType) {
        T result;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            // 配置日期格式序列化、反序列化
            objectMapper.registerModule(new JavaTimeModule());
            result = objectMapper.readValue(json, targetType);
        } catch (IOException e) {
            log.error("JSON反序列化异常,str={}", json, e);
            throw new CustomException("数据格式错误");
        }

        return result;
    }

    /**
     * 对象转换为JSON字符串
     *
     * @param obj 带转换对象
     * @return JSON字符串
     */
    public static String objectToJson(Object obj) {
        String result;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            // 配置日期格式序列化、反序列化
            objectMapper.registerModule(new JavaTimeModule());
            result = objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("JSON序列化异常,obj={}", obj, e);
            throw new CustomException("数据格式转换失败");
        }

        return result;
    }

    /**
     * 对象转换为JSON字符串(不忽略null)
     *
     * @param obj 带转换对象
     * @return JSON字符串
     */
    public static String objectToJsonNull(Object obj) {
        String result;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
            // 配置日期格式序列化、反序列化
            objectMapper.registerModule(new JavaTimeModule());
            result = objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("JSON序列化异常,obj={}", obj, e);
            throw new CustomException("数据格式转换失败");
        }

        return result;
    }

    /**
     * 对象转换为JSON字符串(全属性字段输出)
     *
     * @param obj 带转换对象
     * @return JSON字符串
     */
    public static String objectToJsonWithNull(Object obj) {
        String result;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
            // 配置日期格式序列化、反序列化
            objectMapper.registerModule(new JavaTimeModule());
            result = objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("JSON序列化异常,obj={}", obj, e);
            throw new CustomException("数据格式转换失败");
        }

        return result;
    }

    /**
     * 对象之间转换
     *
     * @param source     来源
     * @param targetType 目标类型
     * @return 转换后的类
     */
    public static <T> T objectToObject(@NotNull Object source, Class<T> targetType) {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.convertValue(source, targetType);
    }

    /**
     * List<Object> 转化为 List<Map<String, Object>>
     * 基本数据类型封装类会报错
     *
     * @param sourceList 来源
     * @return 转换后的类
     */
    public static List<Map<String, Object>> listObjectToListMap(@NotNull List<?> sourceList) {
        ObjectMapper mapper = new ObjectMapper();
        CollectionType mapCollectionType = mapper.getTypeFactory().constructCollectionType(List.class, Map.class);
        return mapper.convertValue(sourceList, mapCollectionType);
    }

    /**
     * object 转化为 map
     * @param o 参数
     * @return map
     */
    public static Map<String, Object> objectToMap(Object o) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        Map map = null;
        try {
            String json = objectMapper.writeValueAsString(o);
            map = objectMapper.readValue(json, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return map;
    }

    public static JsonNode parseNode(String text) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            // 设置输出时包含属性的风格
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            return objectMapper.readTree(text);
        } catch (IOException e) {
            log.warn("parse json error:" + text, e);
            return null;
        }
    }

    public static void main(String[] args) {
        TokenParam param = new TokenParam();
        param.setAppId("123");
        System.out.println(objectToMap(param));
    }


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值