Browse Source

修复Long传到js丢失精度的问题

NorthLan 6 years ago
parent
commit
35017ec318

+ 0 - 8
zen-core/src/main/kotlin/com/gxzc/zen/common/base/BaseModel.kt

@@ -7,10 +7,6 @@ import com.baomidou.mybatisplus.enums.FieldFill
 import com.baomidou.mybatisplus.enums.IdType
 import com.fasterxml.jackson.annotation.JsonFormat
 import com.fasterxml.jackson.annotation.JsonInclude
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize
-import com.fasterxml.jackson.databind.annotation.JsonSerialize
-import com.gxzc.zen.common.config.jackson.LongJsonDeserializer
-import com.gxzc.zen.common.config.jackson.LongJsonSerializer
 import io.swagger.annotations.ApiModelProperty
 import java.io.Serializable
 import java.util.*
@@ -27,14 +23,11 @@ open class BaseModel : Serializable {
 
     // 主键
     @TableId(type = IdType.AUTO)
-    @JsonSerialize(using = LongJsonSerializer::class)
-    @JsonDeserialize(using = LongJsonDeserializer::class)
     var id: Long? = null
 
     // 创建时间
     @TableField(fill = FieldFill.INSERT)
     @ApiModelProperty(hidden = true)
-    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     var createTime: Date? = null
 
     // 创建人id
@@ -43,7 +36,6 @@ open class BaseModel : Serializable {
 
     // 更新时间
     @TableField(fill = FieldFill.UPDATE)
-    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
     var updateTime: Date? = null
 
     // 更新人id

+ 0 - 28
zen-core/src/main/kotlin/com/gxzc/zen/common/config/jackson/LongJsonDeserializer.kt

@@ -1,28 +0,0 @@
-package com.gxzc.zen.common.config.jackson
-
-import com.fasterxml.jackson.core.JsonParser
-import com.fasterxml.jackson.databind.DeserializationContext
-import com.fasterxml.jackson.databind.JsonDeserializer
-import org.slf4j.LoggerFactory
-
-/**
- * String -> Long
- * @author NorthLan
- * @date 2018/5/15
- * @url https://noahlan.com
- */
-class LongJsonDeserializer : JsonDeserializer<Long>() {
-    companion object {
-        private val logger = LoggerFactory.getLogger(LongJsonDeserializer::class.java)
-    }
-
-    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): Long? {
-        val value = p?.text
-        return try {
-            value?.toLong()
-        } catch (e: NumberFormatException) {
-            logger.error("解析长整形错误", e)
-            null
-        }
-    }
-}

+ 0 - 20
zen-core/src/main/kotlin/com/gxzc/zen/common/config/jackson/LongJsonSerializer.kt

@@ -1,20 +0,0 @@
-package com.gxzc.zen.common.config.jackson
-
-import com.fasterxml.jackson.core.JsonGenerator
-import com.fasterxml.jackson.databind.JsonSerializer
-import com.fasterxml.jackson.databind.SerializerProvider
-
-/**
- * Long转String
- * @author NorthLan
- * @date 2018/5/15
- * @url https://noahlan.com
- */
-class LongJsonSerializer : JsonSerializer<Long>() {
-    override fun serialize(value: Long?, gen: JsonGenerator?, serializers: SerializerProvider?) {
-        val text = value?.toString()
-        if (text != null) {
-            gen?.writeString(text)
-        }
-    }
-}

+ 6 - 4
zen-core/src/main/kotlin/com/gxzc/zen/common/config/request/ZenRequestBodyAdvice.kt

@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper
 import com.gxzc.zen.common.config.request.annotation.KVTypeEnum
 import com.gxzc.zen.common.config.request.annotation.ZenRequestTypes
 import com.gxzc.zen.common.dto.RequestDto
+import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.core.MethodParameter
 import org.springframework.http.HttpInputMessage
 import org.springframework.http.converter.HttpMessageConverter
@@ -22,7 +23,8 @@ import java.util.*
 @ControllerAdvice
 class ZenRequestBodyAdvice : RequestBodyAdviceAdapter() {
 
-    private val mapper = ObjectMapper().apply { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) }
+    @Autowired
+    private lateinit var objectMapper: ObjectMapper
 
     override fun supports(methodParameter: MethodParameter, targetType: Type, converterType: Class<out HttpMessageConverter<*>>): Boolean {
         return methodParameter.hasMethodAnnotation(ZenRequestTypes::class.java) && methodParameter.parameterType == RequestDto::class.java
@@ -39,13 +41,13 @@ class ZenRequestBodyAdvice : RequestBodyAdviceAdapter() {
                 val data = typedBody[it.key]
                 when (it.type) {
                     KVTypeEnum.OBJECT -> {
-                        typedBody[it.key] = mapper.convertValue(data, it.value.java)
+                        typedBody[it.key] = objectMapper.convertValue(data, it.value.java)
                     }
                     KVTypeEnum.ARRAY -> {
-                        typedBody[it.key] = mapper.convertValue(data, mapper.typeFactory.constructArrayType(it.value.java))
+                        typedBody[it.key] = objectMapper.convertValue(data, objectMapper.typeFactory.constructArrayType(it.value.java))
                     }
                     KVTypeEnum.LIST -> {
-                        typedBody[it.key] = mapper.convertValue(data, mapper.typeFactory.constructCollectionType(LinkedList::class.java, it.value.java))
+                        typedBody[it.key] = objectMapper.convertValue(data, objectMapper.typeFactory.constructCollectionType(LinkedList::class.java, it.value.java))
                     }
                 }
             }

+ 10 - 7
zen-core/src/main/kotlin/com/gxzc/zen/common/config/response/DynamicFilterResponseBodyAdvice.kt

@@ -1,6 +1,5 @@
 package com.gxzc.zen.common.config.response
 
-import com.fasterxml.jackson.databind.DeserializationFeature
 import com.fasterxml.jackson.databind.ObjectMapper
 import com.gxzc.zen.common.config.response.annotation.ZenResponseFilter
 import com.gxzc.zen.common.config.response.annotation.ZenResponseFilters
@@ -25,12 +24,16 @@ import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJack
 @ControllerAdvice
 class DynamicFilterResponseBodyAdvice : AbstractMappingJacksonResponseBodyAdvice() {
 
+//    @Autowired
+//    @Qualifier(ZenJsonConfigurer.CONVERTER_NAME)
+//    private lateinit var converter: MappingJackson2HttpMessageConverter
+
     @Autowired
-    @Qualifier(ZenJsonConfigurer.CONVERTER_NAME)
-    private lateinit var converter: MappingJackson2HttpMessageConverter
+    private lateinit var objectMapper: ObjectMapper
 
     override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
-        converter.objectMapper = ObjectMapper().apply { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) }
+//        converter.objectMapper = ObjectMapper().apply { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) }
+        objectMapper.setMixIns(null)
         return super.supports(returnType, converterType) &&
                 (returnType.getMethodAnnotation(ZenResponseFilter::class.java) != null
                         || returnType.getMethodAnnotation(ZenResponseFilters::class.java) != null)
@@ -40,14 +43,14 @@ class DynamicFilterResponseBodyAdvice : AbstractMappingJacksonResponseBodyAdvice
         val jsonSerializer = ZenJsonSerializer()
         returnType.methodAnnotations.forEach {
             if (it is ZenResponseFilter) {
-                jsonSerializer.filter(it)
+                jsonSerializer.filter(objectMapper, it)
             } else if (it is ZenResponseFilters) {
                 it.value.forEach {
-                    jsonSerializer.filter(it)
+                    jsonSerializer.filter(objectMapper, it)
                 }
             }
         }
         bodyContainer.filters = jsonSerializer.jacksonFilter
-        converter.objectMapper = jsonSerializer.mapper
+//        converter.objectMapper = jsonSerializer.mapper
     }
 }

+ 0 - 13
zen-core/src/main/kotlin/com/gxzc/zen/common/config/response/FilterConverter.kt

@@ -1,13 +0,0 @@
-package com.gxzc.zen.common.config.response
-
-import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
-
-/**
- * 自定义FilterConverter
- * @author NorthLan
- * @date 2018/3/13
- * @url https://noahlan.com
- */
-class FilterConverter : MappingJackson2HttpMessageConverter() {
-
-}

+ 18 - 2
zen-core/src/main/kotlin/com/gxzc/zen/common/config/response/ZenJsonConfigurer.kt

@@ -1,10 +1,14 @@
 package com.gxzc.zen.common.config.response
 
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer
 import org.springframework.context.annotation.Bean
 import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Primary
 import org.springframework.http.converter.HttpMessageConverter
+import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
+import java.text.SimpleDateFormat
 
 /**
  * 使Spring boot处理自定义jsonhandler
@@ -19,12 +23,24 @@ class ZenJsonConfigurer : WebMvcConfigurerAdapter() {
     }
 
     override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
-        super.configureMessageConverters(converters)
         converters.add(getConverter())
     }
 
     @Bean(CONVERTER_NAME)
     fun getConverter(): MappingJackson2HttpMessageConverter {
-        return MappingJackson2HttpMessageConverter()
+        return MappingJackson2HttpMessageConverter().apply {
+            this.objectMapper = builder().build()
+        }
+    }
+
+    @Bean
+    @Primary
+    fun builder(): Jackson2ObjectMapperBuilder {
+        return Jackson2ObjectMapperBuilder().apply {
+            serializerByType(java.lang.Long::class.java, ToStringSerializer.instance)
+            serializerByType(java.lang.Long.TYPE, ToStringSerializer.instance)
+            // date
+            dateFormat(SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
+        }
     }
 }

+ 5 - 6
zen-core/src/main/kotlin/com/gxzc/zen/common/config/response/ZenJsonSerializer.kt

@@ -1,6 +1,5 @@
 package com.gxzc.zen.common.config.response
 
-import com.fasterxml.jackson.databind.DeserializationFeature
 import com.fasterxml.jackson.databind.ObjectMapper
 import com.gxzc.zen.common.config.response.annotation.ZenResponseFilter
 import kotlin.reflect.KClass
@@ -12,10 +11,10 @@ import kotlin.reflect.KClass
  * @url https://noahlan.com
  */
 class ZenJsonSerializer {
-    val mapper = ObjectMapper().apply { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) }
+    //    val mapper = ObjectMapper().apply { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) }
     val jacksonFilter = ZenJacksonJsonFilter()
 
-    fun filter(clazz: KClass<*>?, include: Array<String>?, filter: Array<String>?) {
+    fun filter(objectMapper: ObjectMapper, clazz: KClass<*>?, include: Array<String>?, filter: Array<String>?) {
         if (clazz == null) {
             return
         }
@@ -25,11 +24,11 @@ class ZenJsonSerializer {
         if (filter != null && filter.isNotEmpty()) {
             jacksonFilter.filter(clazz, filter)
         }
-        mapper.addMixIn(clazz.java, ZenDynamicFilterMixin::class.java)
+        objectMapper.addMixIn(clazz.java, ZenDynamicFilterMixin::class.java)
     }
 
-    fun filter(zenResponseFilter: ZenResponseFilter) {
-        this.filter(zenResponseFilter.type, zenResponseFilter.include, zenResponseFilter.filter)
+    fun filter(objectMapper: ObjectMapper, zenResponseFilter: ZenResponseFilter) {
+        this.filter(objectMapper, zenResponseFilter.type, zenResponseFilter.include, zenResponseFilter.filter)
     }
 
 //    fun toJson(any: Any): String {

+ 0 - 9
zen-orm/src/main/resources/templates/entity.java.vm

@@ -1,10 +1,5 @@
 package ${package.Entity};
 
-#foreach($field in ${table.fields})
-#if(${field.propertyType} == "Date")
-import com.fasterxml.jackson.annotation.JsonFormat;
-#end
-#end
 #foreach($pkg in ${table.importPackages})
 import ${pkg};
 #end
@@ -83,10 +78,6 @@ private static final long serialVersionUID = 1L;
     #if(${logicDeleteFieldName}==${field.name})
     @TableLogic
     #end
-## 日期格式化注解
-    #if(${field.propertyType}=="Date")
-    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
-    #end
 private ${field.propertyType} ${field.propertyName};
 #end
 ## ----------  END 字段循环遍历  ----------

+ 0 - 8
zen-orm/src/main/resources/templates/entity.kt.vm

@@ -1,11 +1,6 @@
 package ${package.Entity}
 
 import com.baomidou.mybatisplus.annotations.TableName
-#foreach($field in ${table.fields})
-#if(${field.propertyType} == "Date")
-import com.fasterxml.jackson.annotation.JsonFormat
-#end
-#end
 #foreach($pkg in ${table.importPackages})
 import ${pkg}
 #end
@@ -69,9 +64,6 @@ open class ${entity} : #if(${superEntityClass})${superEntityClass}#if(${activeRe
 ## 逻辑删除注解
 #if(${logicDeleteFieldName}==${field.name})
 @TableLogic
-#end
-#if(${field.propertyType}=="Date")
-    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
 #end
     var ${field.propertyName}: #if(${field.propertyType} == "Integer")Int#else${field.propertyType}#end? = null#if($foreach.count!=${table.fields.size()})#end
 

+ 21 - 4
zen-web/src/main/kotlin/com/gxzc/zen/web/sys/controller/TestController.kt

@@ -1,11 +1,14 @@
 package com.gxzc.zen.web.sys.controller
 
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.gxzc.zen.api.sys.model.SysUser
 import com.gxzc.zen.common.base.BaseController
+import com.gxzc.zen.common.dto.ResponseDto
+import khronos.Dates
 import org.apache.shiro.SecurityUtils
+import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.http.ResponseEntity
-import org.springframework.web.bind.annotation.GetMapping
-import org.springframework.web.bind.annotation.RequestMapping
-import org.springframework.web.bind.annotation.RestController
+import org.springframework.web.bind.annotation.*
 
 
 /**
@@ -18,6 +21,9 @@ import org.springframework.web.bind.annotation.RestController
 @RequestMapping("test")
 class TestController : BaseController() {
 
+    @Autowired
+    private lateinit var objectMapper: ObjectMapper
+
     @GetMapping("/a")
     fun test() {
 
@@ -38,6 +44,17 @@ class TestController : BaseController() {
     @GetMapping("/long")
     fun longlonglong(): ResponseEntity<*> {
         // 测试long
-        return ResponseEntity.ok(4567890456789045678L)
+        val sysUser = SysUser().apply {
+            id = 123456789012345L
+            createTime = Dates.today
+            updateTime = Dates.tomorrow
+        }
+
+        return ResponseEntity.ok(ResponseDto().apply { data = sysUser })
+    }
+
+    @PostMapping("/longlong")
+    fun longlong(@RequestBody entity: SysUser): ResponseEntity<*> {
+        return ResponseEntity.ok(null)
     }
 }