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

io.github.icodegarden.nutrient.lang.util.JsonUtils Maven / Gradle / Ivy

package io.github.icodegarden.nutrient.lang.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
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 org.springframework.core.ParameterizedTypeReference;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

/**
 * 
 * @author Fangfang.Xu
 */
public abstract class JsonUtils {
	private JsonUtils() {
	}

	public static final DateTimeFormatter STANDARD_DATETIME_FORMATTER = DateTimeFormatter
			.ofPattern("yyyy-MM-dd HH:mm:ss");

	private static ObjectMapper om = new ObjectMapper();
	static {
		om = new ObjectMapper();
		om.setSerializationInclusion(Include.NON_NULL);
		om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		om.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

		JavaTimeModule timeModule = new JavaTimeModule();
		timeModule.addSerializer(LocalDateTime.class, new JsonSerializer() {
			@Override
			public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator,
					SerializerProvider serializerProvider) throws IOException {
				jsonGenerator.writeString(STANDARD_DATETIME_FORMATTER.format(localDateTime));
			}
		});
		timeModule.addDeserializer(LocalDateTime.class, new JsonDeserializer() {
			@Override
			public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
					throws IOException, JsonProcessingException {
				String valueAsString = jsonParser.getValueAsString();
				return LocalDateTime.parse(valueAsString, STANDARD_DATETIME_FORMATTER);
			}
		});
		om.registerModule(timeModule);
	}

	public static boolean isJsonObjectWeakly(String str) {
		if (str != null) {
			return str.startsWith("{") && str.endsWith("}");
		}
		return false;
	}

	public static boolean isJsonArrayWeakly(String str) {
		if (str != null) {
			return str.startsWith("[") && str.endsWith("]");
		}
		return false;
	}

	public static String serialize(Object obj) throws IllegalArgumentException {
		try {
			return om.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new IllegalArgumentException("serialize json error", e);
		}
	}

	public static  T deserialize(String jsonObject, Class cla) throws IllegalArgumentException {
		try {
			return om.readValue(jsonObject, cla);
		} catch (Exception e) {
			throw new IllegalArgumentException("deserialize json error", e);
		}
	}

	/**
	 * 可以反序列化为jsonObject或jsonArray,取决于{@link ParameterizedTypeReference}的泛型类型
	 * 
	 * @param 
	 * @param json
	 * @param typeReference
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static  T deserialize(String json, ParameterizedTypeReference typeReference)
			throws IllegalArgumentException {
		Type responseType = typeReference.getType();
		return deserialize(json, responseType);
	}

	/**
	 * 可以反序列化为jsonObject或jsonArray,取决于responseType的真实类型
	 * 
	 * @param 
	 * @param json
	 * @param responseType
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static  T deserialize(String json, Type responseType) throws IllegalArgumentException {
		try {
			JavaType javaType = om.constructType(responseType);
			return om.readValue(json, javaType);
		} catch (Exception e) {
			throw new IllegalArgumentException("deserialize json error", e);
		}
	}

	/**
	 * 可以反序列化为jsonObject或jsonArray,取决于responseType的真实类型
	 * 
	 * @param 
	 * @param json
	 * @param responseType
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static  T deserialize(InputStream in, Type responseType) throws IllegalArgumentException {
		try {
			JavaType javaType = om.constructType(responseType);
			return om.readValue(in, javaType);
		} catch (Exception e) {
			throw new IllegalArgumentException("deserialize json error", e);
		}
	}

	public static  List deserializeArray(String jsonArray, Class cla) throws IllegalArgumentException {
		try {
			JavaType javaType = om.getTypeFactory().constructParametricType(ArrayList.class, cla);
			return om.readValue(jsonArray, javaType);
		} catch (Exception e) {
			throw new IllegalArgumentException("deserialize json error", e);
		}
	}

	/**
	 * 
	 * @param 

* @param jsonArray * @param cla * @param parametrized 某集合的类型 * @return * @throws IllegalArgumentException */ public static

P deserializeArray(String jsonArray, Class cla, Class

parametrized) throws IllegalArgumentException { try { JavaType javaType = om.getTypeFactory().constructParametricType(parametrized, cla); return om.readValue(jsonArray, javaType); } catch (Exception e) { throw new IllegalArgumentException("deserialize json error", e); } } public static Map deserializeMap(String jsonObject, Class k, Class v) throws IllegalArgumentException { try { JavaType javaType = om.getTypeFactory().constructParametricType(Map.class, k, v); return om.readValue(jsonObject, javaType); } catch (Exception e) { throw new IllegalArgumentException("deserialize json error", e); } } public static ObjectNode put(ObjectNode node, String key, Object value) { if (value == null) { return node; } if (value instanceof String) { return node.put(key, value.toString()); } else if (value instanceof Integer) { return node.put(key, (Integer) value); } else if (value instanceof Long) { return node.put(key, (Long) value); } else if (value instanceof Boolean) { return node.put(key, (Boolean) value); } else if (value instanceof Short) { return node.put(key, (Short) value); } else if (value instanceof Double) { return node.put(key, (Double) value); } else if (value instanceof Float) { return node.put(key, (Float) value); } else if (value instanceof BigDecimal) { return node.put(key, (BigDecimal) value); } else if (value instanceof BigInteger) { return node.put(key, (BigInteger) value); } else if (value instanceof byte[]) { return node.put(key, (byte[]) value); } else if (value instanceof JsonNode) { return node.set(key, (JsonNode) value); } return node; } public static ObjectMapper getObjectMapper() { return om; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy