package com.fengqi.wechat.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/***
 * json 工具类
 * 
 * @author xiewen
 *
 */
public class JsonUtils {
	private final static ObjectMapper objectMapper = new ObjectMapper();
	private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);
	static {
		objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
		// 字段和值都加引号
		objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		// 数字也加引号
		objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
		objectMapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator jg, SerializerProvider sp)
					throws IOException, JsonProcessingException {
				jg.writeString("");
			}
		});
	}

	/**
	 * 
	 * 对象转换成String
	 * 
	 * 
	 * 
	 * @param obj
	 * 
	 * @return
	 * 
	 */
	public static String ObjToString(Object obj) {
		// ObjectMapper mapper = new ObjectMapper();

		String result = "";
		try {
			result = objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			logger.error("JsonUtils ObjToString error: ", e);
		}
		return result;
	}

	/**
	 * 
	 * 将json string反序列化成对象
	 *
	 * 
	 * 
	 * @param json
	 * 
	 * @param valueType
	 * 
	 * @return
	 * 
	 */
	public static <T> T jsonToObj(String json, Class<T> valueType) {
		try {
			return objectMapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("decode(String, Class<T>)", e);
		} catch (JsonMappingException e) {
			logger.error("decode(String, Class<T>)", e);
		} catch (IOException e) {
			logger.error("decode(String, Class<T>)", e);
		}
		return null;
	}

	/**
	 * 
	 * 将json array反序列化为对象
	 *
	 * 
	 * 
	 * @param json
	 * 
	 * @param jsonTypeReference
	 * 
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T jsonToCollection(String json, TypeReference<T> typeReference) {
		try {
			return (T) objectMapper.readValue(json, typeReference);
		} catch (JsonParseException e) {
			logger.error("decode(String, JsonTypeReference<T>)", e);
		} catch (JsonMappingException e) {
			logger.error("decode(String, JsonTypeReference<T>)", e);
		} catch (IOException e) {
			logger.error("decode(String, JsonTypeReference<T>)", e);
		}
		return null;
	}
}
