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

com.lx.util.CollectionUtil Maven / Gradle / Ivy

Go to download

使用文档: https://a7fi97h1rc.feishu.cn/docx/X3LRdtLhkoXQ8hxgXDQc2CLOnEg?from=from_copylink

There is a newer version: 1.1
Show newest version
package com.lx.util;//说明:


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.lx.entity.Var;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * 创建人:游林夕/2019/3/27 15 01
 */
class CollectionUtil {
    /**将对象转为对象*/
    static  T toObj(Class t,Object obj) {
        if (LX.isEmpty(obj)){
            return null;
        }
        if (t.isAssignableFrom(obj.getClass())){
            return (T) obj;
        }
        if (Map.class.isAssignableFrom(t)){
            return (T)toMap((Class)t, obj);
        }
        return parseObject(obj instanceof String?(String)obj:toJSONString(obj),t);
    }
    /**
     * 将对象转为Map
     *  @author
     *  创建时间:2018年4月26日 下午5:35:55
     */
    static T toMap(Class t,Object json) {
        if (json == null){
            return null;
        }
        if (t.isAssignableFrom(json.getClass())){
            return (T) json;
        }
        Map pd = parseObject(json instanceof String?(String)json:toJSONString(json),Map.class);
        T pp = null;
        try {
            pp = t.newInstance();
            for (Object key : pd.keySet()) {
                if(LX.isEmpty(key)){
                    continue;
                }
                Object obj = pd.get(key);
                if(LX.isNotEmpty(obj)){
                    if(obj instanceof Map){
                        pp.put(key, toMap(t,obj));
                    }else if(obj instanceof List){
                        pp.put(key, toList(obj));
                    }else {
                        pp.put(key,obj);
                    }
                }else{
                    pp.put(key, obj);
                }
            }
        } catch (Exception e) {
            LX.exMsg(e);
        }
        return pp;
    }
    public static List toList(Class t,Object obj){
        List list = CollectionUtil.toList(obj);
        List ls = new ArrayList<>();
        if (LX.isNotEmpty(list)){
            list.forEach(v->{
                if (t.isAssignableFrom(v.getClass())){
                    ls.add((T)v);
                }else{
                    ls.add(toObj(t,v));
                }
            });
        }
        return ls;
    }
    /**将对象转为List*/
    static  List toList(Object obj){
        if (obj == null){
            return null;
        }
        List list = null;
        if (List.class.isAssignableFrom(obj.getClass())){
            list = (List) obj;
        }else{
            list =  parseObject(obj instanceof String?(String)obj:toJSONString(obj),List.class);
        }
        List ls = new ArrayList();
        for (Object o : list){
            if(o!=null){
                if(o instanceof Map){
                    ls.add(toMap(Var.class,o));
                }else if(o instanceof List){
                    ls.add(toList(o));
                }else {
                    ls.add(o);
                }
            }else{
                ls.add(o);
            }
        }
        return ls;
    }


    public static  T parseObject(String text, Class clazz) {
        if (LX.isEmpty(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static  T parseObject(byte[] bytes, Class clazz) {
        if (LX.isEmpty(bytes)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(bytes, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static  T parseObject(String text, TypeReference typeReference) {
        if (LX.isEmpty(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static  List parseArray(String text, Class clazz) {
        if (LX.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static final ObjectMapper OBJECT_MAPPER;
    public static final NumberSerializer INSTANCE = new NumberSerializer(Number.class);
    public static final DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
    static {
        Jackson2ObjectMapperBuilder mapperBuilder = new Jackson2ObjectMapperBuilder();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(Long.class, INSTANCE);
        javaTimeModule.addSerializer(Long.TYPE, INSTANCE);
        javaTimeModule.addSerializer(BigInteger.class, INSTANCE);
        javaTimeModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        mapperBuilder.modules(javaTimeModule);
        mapperBuilder.timeZone(TimeZone.getDefault());
        OBJECT_MAPPER = mapperBuilder.build();

        DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter("    ", DefaultIndenter.SYS_LF);
        printer.indentObjectsWith(indenter); // Indent JSON objects
        printer.indentArraysWith(indenter);  // Indent JSON arrays
    }

    static String toJSONString(Object obj) {
        if (obj == null){
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }



    //说明:格式化输出json字符串
    /**{ ylx } 2019/8/12 10:04 */
    static String toFormatJson(Object obj) {
        try {
            return OBJECT_MAPPER.writer(printer).writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}






© 2015 - 2025 Weber Informatics LLC | Privacy Policy