All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.fufu669.utils.CacheJsonUtil Maven / Gradle / Ivy

There is a newer version: 6.666.66021
Show newest version
package com.gitee.fufu669.utils;


import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({ "unchecked" })
/** @author wangfupeng */
public class CacheJsonUtil {

    public static final Logger logger = LoggerFactory.getLogger(CacheJsonUtil.class);

    private static ThreadLocal objMapperLocal = new ThreadLocal() {
        @Override
        public ObjectMapper initialValue() {
            ObjectMapper mapper = new ObjectMapper();
            return mapper;
        }
    };

    public static  String toJson(T obj) {
        return JSON.toJSONString(obj);
    }

    public static  T toObject(String jsonStr, Class cls) {
        return JSON.parseObject(jsonStr, cls);
    }

    public static  T toObject(Object jsonObject, Class cls) {
        return JSON.parseObject(toJson(jsonObject), cls);
    }

    
    public static  List toList(String jsonString, Class clazz) {
        try {
            ObjectMapper mapper = objMapperLocal.get();
            return (List) mapper.readValue(jsonString, mapper.getTypeFactory()
                    .constructParametricType(List.class, clazz));
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        return new ArrayList<>();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy