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

com.feingto.cloud.kit.json.JSON Maven / Gradle / Ivy

There is a newer version: 2.5.2.RELEASE
Show newest version
package com.feingto.cloud.kit.json;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * json字符串、对象、List转换工具类
 *
 * @author longfei
 */
public class JSON {
    private static volatile JSON instance;
    private final JSONObjectMapper objectMapper = new JSONObjectMapper();
    private final XmlMapper xmlMapper = new XmlMapper();

    public static JSON getInstance() {
        if (Objects.isNull(instance)) {
            synchronized (JSON.class) {
                if (Objects.isNull(instance)) {
                    instance = new JSON();
                }
            }
        }
        return instance;
    }

    /**
     * 过滤属性,配置@JsonFilter(filterName)使用
     */
    public JSON filter(String filterName, String... properties) {
        FilterProvider filterProvider = new SimpleFilterProvider().addFilter(filterName,
                SimpleBeanPropertyFilter.serializeAllExcept(properties));
        objectMapper.setFilterProvider(filterProvider);
        return this;
    }

    public static ObjectNode JSONObject() {
        return getInstance().objectMapper.createObjectNode();
    }

    public static ArrayNode JSONArray() {
        return getInstance().objectMapper.createArrayNode();
    }

    @SneakyThrows
    public static JsonNode read(String json) {
        return StringUtils.hasText(json) ? getInstance().objectMapper.readTree(json) : JSONObject();
    }

    @SneakyThrows
    public static JsonNode readXml(String json) {
        return StringUtils.hasText(json) ? getInstance().xmlMapper.readTree(json) : JSONObject();
    }

    /**
     * byte[] read to JsonNode
     */
    @SneakyThrows
    public static JsonNode read(byte[] bytes) {
        return getInstance().objectMapper.readTree(bytes);
    }

    /**
     * inputStream read to JsonNode
     */
    @SneakyThrows
    public static JsonNode read(InputStream inputStream) {
        return getInstance().objectMapper.readTree(inputStream);
    }

    /**
     * json string convert to xml string
     */
    @SneakyThrows
    public static String json2xml(String json) {
        return StringUtils.hasText(json) ? getInstance().xmlMapper.writeValueAsString(read(json)) : "";
    }

    /**
     * pojo convert to json string
     */
    @SneakyThrows
    public static String obj2json(Object pojo) {
        return Objects.nonNull(pojo) ? getInstance().objectMapper.writeValueAsString(pojo) : "";
    }

    /**
     * json string convert to javaBean
     */
    @SneakyThrows
    public static  T json2pojo(String json, Class clazz) {
        return StringUtils.hasText(json) ? getInstance().objectMapper.readValue(json, clazz) : null;
    }

    /**
     * json string convert to map with javaBean
     */
    @SneakyThrows
    public static  Map json2map(String json, Class clazz) {
        Map map = getInstance().objectMapper.readValue(json,
                new TypeReference>() {
                });
        Map result = new HashMap<>();
        map.forEach((key, value) -> result.put(key, object2pojo(value, clazz)));
        return result;
    }

    /**
     * json string convert to list with javaBean
     */
    @SuppressWarnings("unchecked")
    @SneakyThrows
    public static  List json2list(String json, Class clazz) {
        return StringUtils.hasText(json) ? (List) getInstance().objectMapper.readValue(json, getCollectionType(clazz))
                : new ArrayList<>();
    }

    /**
     * object convert to javaBean
     */
    public static  T object2pojo(Object obj, Class clazz) {
        return Objects.nonNull(obj) ? getInstance().objectMapper.convertValue(obj, clazz) : null;
    }

    /**
     * object convert to list with javaBean
     */
    public static  Map object2Map(Object obj) {
        return Objects.nonNull(obj) ? getInstance().objectMapper.convertValue(obj,
                new TypeReference>() {
                }) : new HashMap<>();
    }

    /**
     * object convert to list with javaBean
     */
    public static  List object2list(Object obj, Class clazz) {
        return Objects.nonNull(obj) ? getInstance().objectMapper.convertValue(obj,
                new TypeReference>>() {
                }).stream()
                .map(map -> object2pojo(map, clazz))
                .collect(Collectors.toList()) : new ArrayList<>();
    }

    /**
     * format javaBean
     */
    @SneakyThrows
    public static  String format(T entity) {
        return Objects.nonNull(entity) ? getInstance().objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity) : "";
    }

    /**
     * 结果集合集
     */
    public static String reduce(List list) {
        return list.stream()
                .reduce((l, r) -> {
                    ObjectNode node = JSONObject();
                    l.fields().forEachRemaining(it -> node.set(it.getKey(), it.getValue()));
                    r.fields().forEachRemaining(it -> node.set(it.getKey(), it.getValue()));
                    return node;
                })
                .orElse(JSONObject()).toString();
    }

    /**
     * 获取泛型的Collection Type
     */
    private static JavaType getCollectionType(Class... elementClasses) {
        return getInstance().objectMapper.getTypeFactory().constructParametricType(ArrayList.class, elementClasses);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy