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)
}
posted @ 2017-09-20 23:03  NewSea  阅读(1082)  评论(0编辑  收藏  举报