SpringBoot笔记--FastJson
FastJson配置 ObjectId
class ObjectIdSerializer : ObjectSerializer {
override fun write(serializer: JSONSerializer?, value: Any?, filedName: Any?, fieldType: Type?, features: Int) {
val out = serializer!!.getWriter()
if (value == null) {
out.writeNull()
return
}
out.writeString(value.toString())
}
}
@Configuration
open class MyWebMvcConfig : WebMvcConfigurerAdapter() {
override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>?) {
val fastConverter = FastJsonHttpMessageConverter()
val fastJsonConfig = FastJsonConfig()
// fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat)
fastJsonConfig.serializeConfig.put(ObjectId::class.java, ObjectIdSerializer());
fastConverter.fastJsonConfig = fastJsonConfig
//处理中文乱码问题
fastConverter.supportedMediaTypes = mutableListOf(MediaType.APPLICATION_JSON_UTF8)
var stringMessageConvert = StringHttpMessageConverter();
stringMessageConvert.setWriteAcceptCharset(false)
stringMessageConvert.supportedMediaTypes = mutableListOf(MediaType.ALL)
stringMessageConvert.defaultCharset = Charset.forName("utf-8")
converters!!.add(stringMessageConvert);
converters!!.add(fastConverter)
}
}
ParserConfig.getGlobalInstance().putDeserializer(ObjectId::class.java, ObjectIdDeserializer())
class ObjectIdDeserializer : ObjectDeserializer {
override fun <T> deserialze(parser: DefaultJSONParser, type: Type,
fieldName: Any): T {
val lexer = parser.getLexer()
val value = lexer.stringVal()
return ObjectId(value) as T;
}
override fun getFastMatchToken(): Int {
// TODO Auto-generated method stub
return 0
}
}
fun <T> T.ToJson(): String {
if (this is String) return this;
val filter = ValueFilter { source, name, value ->
if (value is ObjectId) {
return@ValueFilter value.toString();
}
value;
}
// var sc = SerializeConfig();
// sc.put(ObjectId::class.java, ObjectIdSerializer());
return JSON.toJSONString(this, filter)
}
作者:NewSea 出处:http://newsea.cnblogs.com/
QQ,MSN:iamnewsea@hotmail.com 如无特别标记说明,均为NewSea原创,版权私有,翻载必纠。欢迎交流,转载,但要在页面明显位置给出原文连接。谢谢。 |