package com.dcit.common.utils;

import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.fasterxml.jackson.core.JsonGenerator;

/**
 * 返回json中null值转为空字符串，数组转为空数组
 * @author zhangzhizhong
 *
 */
public class MyJsonMapper extends ObjectMapper {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public MyJsonMapper() {
		super();
		//收到未知属性时不报异常
		this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
		//Long类型转为String类型
		//SimpleModule simpleModule = new SimpleModule();
		//simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		//simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
		//this.registerModule(simpleModule);
		//处理空指针时设置的值
		this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
				String fieldName = gen.getOutputContext().getCurrentName();
				try {
					//反射获取字段类型
					Field field = gen.getCurrentValue().getClass().getDeclaredField(fieldName);
					if (Objects.equals(field.getType(), String.class)) {
						//字符串型空值""
						gen.writeString("");
						return;
					} else if (Objects.equals(field.getType(), List.class)) {
						//列表型空值返回[]
						gen.writeStartArray();
						gen.writeEndArray();
						return;
					} else if (Objects.equals(field.getType(), Map.class)) {
						//map型空值返回{}
						gen.writeStartObject();
						gen.writeEndObject();
						return;
					}
				} catch (NoSuchFieldException e) {
				}
				//默认返回""
				gen.writeString("");
			}
		});
	}

}
