package cn.pluss.platform.configurer.extend;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.Collections;

public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {
	private static final SerializerFeature[] features = {
			// 输出空置字段
			SerializerFeature.WriteMapNullValue,
			// list字段如果为null，输出为[]，而不是null
			SerializerFeature.WriteNullListAsEmpty,
			// 数值字段如果为null，输出为0，而不是null
			// SerializerFeature.WriteNullNumberAsZero,
			// SerializerFeature.WriteNullBooleanAsFalse,
			// Boolean字段如果为null，输出为false，而不是null
			// 字符类型字段如果为null，输出为""，而不是null
			SerializerFeature.WriteNullStringAsEmpty,
			// 关闭引用检测，解决$ref问题
			SerializerFeature.DisableCircularReferenceDetect
	};

	public FastJsonHttpMessageConverterEx() {
		FastJsonConfig fastJsonConfig = getFastJsonConfig();
		fastJsonConfig.setSerializerFeatures(features);
		fastJsonConfig.setFeatures();
		fastJsonConfig.setSerializeFilters();
		setDefaultCharset(StandardCharsets.UTF_8);
		setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));

		ParserConfig globalInstance = ParserConfig.getGlobalInstance();
		// 只能过滤部分。对于接受参数为实体类的无法生效
		StringDeserializer stringDeserializer = new StringDeserializer();
		globalInstance.putDeserializer(String.class, stringDeserializer);
		globalInstance.putDeserializer(StringBuilder.class, stringDeserializer);
		globalInstance.putDeserializer(StringBuffer.class, stringDeserializer);
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return super.supports(clazz);
	}
}
