JsonUtil工具类

 JsonUtils

package com.foo.bar.framework.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.foo.bar.framework.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * Json工具类
 *
 * @author foobar
 * @date 2020/8/7 15:16
 */
@Slf4j
public class JsonUtil {

    private JsonUtil() {
        throw new UnsupportedOperationException();
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

    static {
        //对象的所有字段全部列入
        MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //取消默认转换timestamps形式
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //忽略空Bean转json的错误
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
        MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
        //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 转为JSON字符串
     *
     * @param object object
     * @return JSON字符串
     */
    public static String toJsonString(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 转为JSON字符串
     * 如果字段上加了 @JsonFormat 此处的dateFormatPattern将不会生效
     *
     * @param object            object
     * @param dateFormatPattern 时间格式
     * @return JSON字符串
     */
    public static String toJsonStringWithDateFormat(Object object, String dateFormatPattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern);
        try {
            return MAPPER.writer(sdf).writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 转为实体类对象,转换异常将被抛出
     *
     * @param <T>      Bean类型
     * @param json     json字符串
     * @param beanType 实体类对象类型
     * @return 实体类对象
     */
    public static <T> T toBean(String json, Class<T> beanType) {
        try {
            return MAPPER.readValue(json, beanType);
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 转为实体类对象,转换异常将被抛出
     *
     * @param <V>       Bean类型
     * @param json      json字符串
     * @param valueType Map value实体类对象类型
     * @return 实体类对象
     */
    public static <V> Map<String, V> toMap(String json, Class<V> valueType) {
        JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, String.class, valueType);
        try {
            return MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * 转为实体类对象,转换异常将被抛出
     *
     * @param <T>      Bean类型
     * @param json     json字符串
     * @param beanType List泛型实体类对象类型
     * @return 实体类对象
     */
    public static <T> List<T> toList(String json, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructCollectionType(List.class, beanType);
        try {
            return MAPPER.readValue(json, javaType);
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    /**
     * object转map
     *
     * @param fromValue object
     * @return Map<String, Object>
     */
    public static Map<String, Object> beanToMap(Object fromValue) {
        JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, String.class, Object.class);
        return MAPPER.convertValue(fromValue, javaType);
    }


    /**
     * map转Bean
     *
     * @param fromMap     Map<String,Object>
     * @param toValueType Map value类型
     * @param <T>         Bean类型
     * @return Bean
     */
    public static <T> T mapToBean(Map<String, Object> fromMap, Class<T> toValueType) {
        return MAPPER.convertValue(fromMap, toValueType);
    }

}

 JsonUtils测试类

package com.foo.bar.framework.utils;

import lombok.Data;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtilTest {

    private static final String YMD_FORMAT = "yyyy-MM-dd";


    private static final String expectedString = "{\"userName\":\"张三\",\"userCode\":\"1\",\"tradeDate\":\"2020-08-16 08:00:19\",\"userId\":1}";
    private static final String expectedWithDateFormatString = "{\"userName\":\"张三\",\"userCode\":\"1\",\"tradeDate\":\"2020-08-16\",\"userId\":1}";
    private static final String expectedListString = "[{\"userName\":\"张三\",\"userCode\":\"1\",\"tradeDate\":\"2020-08-16 08:00:19\",\"userId\":1},{\"userName\":\"李四\",\"userCode\":\"1\",\"tradeDate\":\"2021-08-16 08:00:19\",\"userId\":2}]";
    private static final String expectedMapString = "{\"1\":{\"userName\":\"张三\",\"userCode\":\"1\",\"tradeDate\":\"2020-08-16 08:00:19\",\"userId\":1}}";

    private static UserTest expectBean;
    private static List<UserTest> expectBeanList;
    private static Map<String, Object> expectMap;
    private static Map<String, Object> expectBeanMap;
    private static Map<String, Object> expectBeanWithDateStringMap;

    @Before
    public void before() {
        expectBean = new UserTest();
        expectBean.setUserCode("1");
        expectBean.setUserName("张三");
        expectBean.setTradeDate(DateUtil.strToDate("2020-08-16 08:00:19"));
        expectBean.setUserId(1L);

        expectBeanList = new ArrayList<>();
        expectBeanList.add(expectBean);
        UserTest userTest2 = new UserTest();
        userTest2.setUserCode("1");
        userTest2.setUserName("李四");
        userTest2.setTradeDate(DateUtil.strToDate("2021-08-16 08:00:19"));
        userTest2.setUserId(2L);
        expectBeanList.add(userTest2);

        expectMap = new HashMap<>();
        expectMap.put("1", expectBean);

        expectBeanMap = new HashMap<>();
        expectBeanMap.put("userCode", expectBean.getUserCode());
        expectBeanMap.put("userName", expectBean.getUserName());
        expectBeanMap.put("tradeDate", expectBean.getTradeDate());
        expectBeanMap.put("userId", 1L);

        expectBeanWithDateStringMap = new HashMap<>();
        expectBeanWithDateStringMap.put("userCode", expectBean.getUserCode());
        expectBeanWithDateStringMap.put("userName", expectBean.getUserName());
        expectBeanWithDateStringMap.put("tradeDate", "2020-08-16 08:00:19");
        expectBeanWithDateStringMap.put("userId", 1L);


    }

    @Test
    public void toJsonString() {
        final String jsonString = JsonUtil.toJsonString(expectBean);
        Assert.assertEquals(expectedString, jsonString);
        final String userListJsonString = JsonUtil.toJsonString(expectBeanList);
        Assert.assertEquals(expectedListString, userListJsonString);
        final String userMapJsonString = JsonUtil.toJsonString(expectMap);
        Assert.assertEquals(expectedMapString, userMapJsonString);
    }

    @Test
    public void toJsonStringWithDateFormat() {
        final String jsonString = JsonUtil.toJsonStringWithDateFormat(expectBean, YMD_FORMAT);
        Assert.assertEquals(expectedWithDateFormatString, jsonString);
    }

    @Test
    public void toBean() {
        final UserTest actual = JsonUtil.toBean(expectedString, UserTest.class);
        Assert.assertEquals(expectBean, actual);
    }

    @Test
    public void toMap() {
        final Map<String, UserTest> actual = JsonUtil.toMap(expectedMapString, UserTest.class);
        Assert.assertEquals(expectMap, actual);
    }

    @Test
    public void toList() {
        final List<UserTest> actual = JsonUtil.toList(expectedListString, UserTest.class);
        Assert.assertEquals(expectBeanList, actual);
    }

    @Test
    public void beanToMap() {
        final Map<String, Object> actualMap = JsonUtil.beanToMap(expectBean);
        String expectString = "{\"userName\":\"张三\",\"userCode\":\"1\",\"tradeDate\":\"2020-08-16 08:00:19\",\"userId\":1}";
        Assert.assertEquals(expectString, JsonUtil.toJsonString(actualMap));
        UserTest actualBean = JsonUtil.mapToBean(actualMap, UserTest.class);
        Assert.assertEquals(expectBean, actualBean);
        //Date 类型的会转换成 yyyy-MM-dd HH:mm:ss
        Assert.assertEquals(expectBeanMap, actualMap);

    }


    @Test
    public void mapToBean() {
        final UserTest actual = JsonUtil.mapToBean(expectBeanMap, UserTest.class);
        Assert.assertEquals(expectBean, actual);
        final UserTest actual2 = JsonUtil.mapToBean(expectBeanWithDateStringMap, UserTest.class);
        Assert.assertEquals(expectBean, actual2);
    }

    @Data
    private static class UserTest {
        private String userName;
        private String userCode;
        private Date tradeDate;
        private Long userId;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值