jackson json

614 阅读2分钟

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.wingbow.dss.common.config.exception.ClientErrorException;
import com.wingbow.dss.util.DateUtil.Pattern;

public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		JavaTimeModule javaTimeModule = new JavaTimeModule();
		javaTimeModule.addSerializer(LocalDateTime.class,
				new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(Pattern.LONG_PATTERN.getFormat())));
		javaTimeModule.addSerializer(LocalDate.class,
				new LocalDateSerializer(DateTimeFormatter.ofPattern(Pattern.SHORT_PATTERN.getFormat())));
		javaTimeModule.addSerializer(LocalTime.class,
				new LocalTimeSerializer(DateTimeFormatter.ofPattern(Pattern.TIME_PATTERN.getFormat())));

		javaTimeModule.addDeserializer(LocalDateTime.class,
				new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(Pattern.LONG_PATTERN.getFormat())));
		javaTimeModule.addDeserializer(LocalDate.class,
				new LocalDateDeserializer(DateTimeFormatter.ofPattern(Pattern.SHORT_PATTERN.getFormat())));
		javaTimeModule.addDeserializer(LocalTime.class,
				new LocalTimeDeserializer(DateTimeFormatter.ofPattern(Pattern.TIME_PATTERN.getFormat())));
		objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
    }

    public static String pojo2Json(Object object) {
        if (object == null) {
            return "";
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("json转换异常", e);
			throw new ClientErrorException("json转换异常");
        }
    }

    /**
     * 将 JSON 字符串转为 Java 对象
     * @param <T> 
     * @param json 
     * @param type 
     * @return 
     */
    public static <T> T fromJSON(String json, Class<T> type) {
        try {
            return  objectMapper.readValue(json, type);
        } catch (Exception e) {
            logger.error(String.format("json转换异常json:%s", json), e);
			throw new ClientErrorException("json转换异常");
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> fromJSONToList(String json, Class<T> type) {
        JavaType javaType = getCollectionType(List.class, type);
        try {
            return (List<T>) objectMapper.readValue(json, javaType);
        } catch (Exception e) {
        	logger.error(String.format("json转换异常json:%s###class:%s", json,type.getTypeName()), e);
			throw new ClientErrorException("json转换异常");
        }
        
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?> elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }


    /**
     * 将list中的对象转换为其他对象的list
     * @param <T> 
     * @param pageData 
     * @param type 
     * @return 
     */
    public static <T> T fromJSON(List<?> pageData, Class<T> type) {
        return fromJSON(pojo2Json(pageData), type);
    }

    /**
     * 将 JSON 字符串转为 Java 对象
     * @param <T> 
     * @param json 
     * @param jsonNodeFieldPath 
     * @param type 
     * @return 
     */
    public static <T> T fromJSON(String json, List<String> jsonNodeFieldPath, Class<T> type) {
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            for (String  fieldName: jsonNodeFieldPath) {
                jsonNode = jsonNode.findValue(fieldName);
            }

            return fromJSON(jsonNode.toString(), type);
        } catch (IOException e) {
            logger.error("json转换异常", e);
			throw new ClientErrorException("json转换异常");
        }
    }

    /**
     * 将 JSON特定field的字符串转为 Java 对象
     * @param <T> 
     * @param json 
     * @param fieldName 
     * @param type 
     * @return 
     */
    public static <T> T fromJSON(String json, String fieldName, Class<T> type) {
        return fromJSON(json, Arrays.asList(fieldName), type);
    }

    /**
     * 判断指定的节点下是否有值
     * 
     * @param json
     * @param fieldName
     * @return
     */
    public static boolean hasField(String json, String fieldName) {
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            return jsonNode.has(fieldName);
        } catch (IOException e) {
            logger.error("json转换异常", e);
			throw new ClientErrorException("json转换异常");
        }
    }

}