JsonUtils工具类

JsonUtils工具类

在使用Json的时候,经常要进行一些转换,例如Bean转Json,Json转Bean,还有List、Map与Bean之间的转换,我们可以封装一个工具类,简化其操作。

所需依赖:

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

JsonUtils工具类:

package com.leyou.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author: rayfoo
 * @create: 2020-06-25 17:20
 **/
public class JsonUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * 转为json
     *
     * @param obj
     * @return
     */
    public static String serialize(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化出错:" + obj, e);
            return null;
        }
    }

    /**
     * JSON转POJO
     *
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T parse(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    /**
     * JSON数组转List
     *
     * @param json
     * @param eClass
     * @param <E>
     * @return
     */
    public static <E> List<E> parseList(String json, Class<E> eClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }



    /**
     * Json、Json数组转Map
     *
     * @param json
     * @param kClass
     * @param vClass
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> Map<K, V> parseMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }


    /**
     * 万能转换
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

}

测试类,演示使用:

package com.leyou.test;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.junit.Test;

import java.util.List;
import java.util.Map;

/**
 * @Author: rayfoo@qq.com
 * @Date: 2020/7/6 5:23 下午
 * @Description:
 */
public class TestApp {



    @Test
    public void test01(){
        Person p = new Person(18,"asd");
        String serialize = JsonUtils.serialize(p);
        System.out.println(serialize);

    }

    @Test
    public void test02(){
        String json = "{\"id\":18,\"name\":\"asd\"}";
        Person parse = JsonUtils.parse(json, Person.class);
        System.out.println(parse);
    }

    @Test
    public void test03(){
        String json = "[1,3,4,67,-12]";
        List<Integer> integers = JsonUtils.parseList(json, Integer.class);
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

    @Test
    public void test04(){
        String json = "{\"name\": \"rayfoo\", " +
                " \"id\": 18 " +
                "}";
        Map<String, Object> map = JsonUtils.parseMap(json, String.class, Object.class);
        System.out.printf("map=" + map);
    }

    @Test
    public void test05(){
        String json = "[{\"name\": \"rayfoo\",\n" +
                "  \"id\": 22\n" +
                "},{\"name\": \"rayfoo\",\n" +
                "  \"id\": 22\n" +
                "},{\"name\": \"rayfoo\",\n" +
                "  \"id\": 24\n" +
                "}]";
        List<Map<String, Object>> maps = JsonUtils.nativeRead(json, new TypeReference<List<Map<String, Object>>>() {

        });
        for (Map<String, Object> map : maps) {
            System.out.println("map=" + map);
        }
    }

    @Test
    public void test06(){
        String json = "[{\"name\": \"rayfoo\",\n" +
                "  \"id\": 22\n" +
                "},{\"name\": \"rayfoo\",\n" +
                "  \"id\": 22\n" +
                "},{\"name\": \"rayfoo\",\n" +
                "  \"id\": 24\n" +
                "}]";
        List<Person> people = JsonUtils.nativeRead(json, new TypeReference<List<Person>>() {
        });
        for (Person person : people) {
            System.out.println("person=" + person);
        }
    }


}

posted @ 2020-06-26 20:27  张瑞丰  阅读(3488)  评论(0编辑  收藏  举报