【java】JacksonUtils工具类

JacksonConfig

package com.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * <p>
 * <code>JacksonConfig</code>
 * </p>
 * Description:
 *
 */
@Configuration
@ConditionalOnMissingBean({ObjectMapper.class})
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
        ObjectMapper objectMapper = jackson2ObjectMapperBuilder.createXmlMapper(false).build();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        return objectMapper;
    }
}

JacksonUtils

package com.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * <code>JacksonUtils </code>
 * </p>
 * Description:
 */
@Slf4j
public class JacksonUtils {

    private final static ObjectMapper OBJECT_MAPPER = SpringContextUtils.getBean(ObjectMapper.class);

    /**
     * 转字符串
     *
     * @param o
     * @return
     */
    public static String toString(Object o) {
        try {
            if (o != null) {
                return OBJECT_MAPPER.writeValueAsString(o);
            }
        } catch (Exception e) {
            log.error("==> toString error", e);
        }
        return null;
    }

    /**
     * 字符串转对象
     *
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T toObject(String json, Class<T> valueType) {
        try {
            return StringUtils.isNotBlank(json) && !"null".equalsIgnoreCase(json) ?
                    OBJECT_MAPPER.readValue(json, valueType) : null;
        } catch (Exception e) {
            log.error("==> toObject error", e);
        }
        return null;
    }

    /**
     * 字符串转数组
     *
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T[] toArray(String json, Class<T> valueType) {
        try {
            if (StringUtils.isNotBlank(json) && !"null".equalsIgnoreCase(json)) {
                ArrayType arrayType = OBJECT_MAPPER.getTypeFactory().constructArrayType(valueType);
                return OBJECT_MAPPER.readValue(json, arrayType);
            }
        } catch (Exception e) {
            log.error("==> toArray error", e);
        }
        return null;
    }

    /**
     * 字符串转集合
     *
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(String json, Class<T> valueType) {
        List<T> list = Lists.newArrayList();
        try {
            if (StringUtils.isNotBlank(json) && !"null".equalsIgnoreCase(json)) {
                CollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(ArrayList.class, valueType);
                List<T> value = OBJECT_MAPPER.readValue(json, listType);
                if (!CollectionUtils.isEmpty(value)) {
                    list.addAll(value);
                }
            }
        } catch (Exception e) {
            log.error("==> toList error", e);
        }
        return list;
    }

    /**
     * 字符串转JsonNode  可操作性高
     *
     * @param json
     * @return
     */
    public static JsonNode toJsonNode(String json) {
        try {
            return StringUtils.isNotBlank(json) && !"null".equalsIgnoreCase(json) ?
                    OBJECT_MAPPER.readTree(json) : null;
        } catch (Exception e) {
            log.error("==> toJsonNode error", e);
        }
        return null;
    }

    /**
     * 转对象
     *
     * @param jsonNode
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T toObject(JsonNode jsonNode, Class<T> valueType) {
        try {
            return toObject(toString(jsonNode), valueType);
        } catch (Exception e) {
            log.error("==> toObject error", e);
        }
        return null;
    }

    public static JsonNode getJsonNode(JsonNode jsonNode, String fieldName) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            return jsonNode.get(fieldName);
        }
        return null;
    }

    public static String getString(JsonNode jsonNode, String fieldName) {
        return getString(jsonNode, fieldName, null);
    }

    public static int getInteger(JsonNode jsonNode, String fieldName) {
        return getInteger(jsonNode, fieldName, 0);
    }

    public static long getLong(JsonNode jsonNode, String fieldName) {
        return getLong(jsonNode, fieldName, 0L);
    }

    public static boolean getBoolean(JsonNode jsonNode, String fieldName) {
        return getBoolean(jsonNode, fieldName, false);
    }

    public static String getString(JsonNode jsonNode, String fieldName, String defaultValue) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            String result = jsonNode.get(fieldName).asText();
            return "null".equalsIgnoreCase(result) ? null : result;
        }
        return defaultValue;
    }

    public static Integer getInteger(JsonNode jsonNode, String fieldName, Integer defaultValue) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            return jsonNode.get(fieldName).intValue();
        }
        return defaultValue;
    }

    public static Long getLong(JsonNode jsonNode, String fieldName, Long defaultValue) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            return jsonNode.get(fieldName).longValue();
        }
        return defaultValue;
    }

    public static Boolean getBoolean(JsonNode jsonNode, String fieldName, Boolean defaultValue) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            return jsonNode.get(fieldName).booleanValue();
        }
        return defaultValue;
    }

    public static List<JsonNode> findValues(JsonNode jsonNode, String fieldName) {
        if (jsonNode != null && jsonNode.has(fieldName)) {
            return jsonNode.findValues(fieldName);
        } else {
            return Lists.newArrayList();
        }
    }
}

SpringContextUtils

package com.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Spring ApplicationContext 工具类
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader("Origin");
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 发布事件
     *
     * @param event
     */
    public static void publishEvent(ApplicationEvent event) {
        if (applicationContext == null) {
            return;
        }
        applicationContext.publishEvent(event);
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值