This commit is contained in:
2026-03-11 08:47:22 +08:00
parent 450b4e1a93
commit bc8927db26
71 changed files with 4474 additions and 2471 deletions
@@ -0,0 +1,217 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJackson3Module
import tools.jackson.core.type.TypeReference
import tools.jackson.databind.JsonNode
import tools.jackson.databind.ObjectMapper
import tools.jackson.databind.node.ObjectNode
import java.lang.reflect.Type
class Jackson3JsonApi : JsonApi {
var get: () -> ObjectMapper
var set: (ObjectMapper) -> Unit
private var _prObjectMapper: ObjectMapper? = null
private var objectMapper: ObjectMapper
get() = get()
set(value) = set(value)
constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper
get = { _prObjectMapper!! }
set = { _prObjectMapper = it }
}
constructor(
get: () -> ObjectMapper,
set: (ObjectMapper) -> Unit,
) {
this.get = get
this.set = set
}
override fun <T> parse(json: String, clazz: Class<T>): T {
try {
return objectMapper.readValue(json, clazz)
} catch (e: Exception) {
throw JsonException("Failed to parse JSON to ${clazz.simpleName}", e)
}
}
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
try {
return objectMapper.readValue(json, object : TypeReference<T>() {
override fun getType(): Type = type.type
})
} catch (e: Exception) {
throw JsonException("Failed to parse JSON to type: $type", e)
}
}
override fun format(obj: Any): String {
try {
return objectMapper.writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException("Failed to format object to JSON: ${obj.javaClass.simpleName}", e)
}
}
override fun formatPretty(obj: Any): String {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException("Failed to format object to pretty JSON: ${obj.javaClass.simpleName}", e)
}
}
override fun isValidJson(json: String): Boolean {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
false
}
}
override fun merge(vararg jsons: String): String {
try {
if (jsons.isEmpty()) return "{}"
val resultNode = objectMapper.createObjectNode()
for (json in jsons) {
val node = objectMapper.readTree(json)
if (node is ObjectNode) {
resultNode.setAll(node)
} else {
throw JsonException("Cannot merge non-object JSON: $json")
}
}
return objectMapper.writeValueAsString(resultNode)
} catch (e: Exception) {
throw JsonException("Failed to merge JSON objects", e)
}
}
override fun getNodeValue(json: String, path: String): String? {
try {
val rootNode = objectMapper.readTree(json)
val node = rootNode.at(path)
return if (node.isMissingNode || node.isNull) {
null
} else {
node.asString()
}
} catch (e: Exception) {
throw JsonException("Failed to get node value at path: $path", e)
}
}
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
try {
val rootNode = objectMapper.readTree(json)
// 处理 JSON Pointer 路径
val pathParts = path.split("/").filter { it.isNotEmpty() }
if (pathParts.isEmpty()) {
// 替换整个根节点
return objectMapper.writeValueAsString(newValue)
}
when (val parentNode = findParentNode(rootNode, pathParts)) {
is ObjectNode -> {
val fieldName = pathParts.last()
val valueNode = objectMapper.valueToTree<JsonNode>(newValue)
parentNode.replace(fieldName, valueNode)
}
else -> {
throw JsonException("Cannot update node: parent is not an object node at path: $path")
}
}
return objectMapper.writeValueAsString(rootNode)
} catch (e: Exception) {
throw JsonException("Failed to update node value at path: $path", e)
}
}
override fun <D> convert(source: Any, destinationClass: Class<D>): D {
try {
return objectMapper.convertValue(source, destinationClass)
} catch (e: Exception) {
throw JsonException(
"Failed to convert from ${source.javaClass.simpleName} to ${destinationClass.simpleName}",
e
)
}
}
override fun <D> convert(
source: Any,
destinationType: JsonTypeReference<D>,
): D {
try {
return objectMapper.convertValue(source, object : TypeReference<D>() {
override fun getType(): Type = destinationType.type
})
} catch (e: Exception) {
throw JsonException("Failed to convert from ${source.javaClass.simpleName} to type: $destinationType", e)
}
}
// 辅助方法:查找父节点
private fun findParentNode(root: JsonNode, pathParts: List<String>): JsonNode {
var current: JsonNode = root
// 遍历到最后一个元素之前(即找到父节点)
for (i in 0 until pathParts.size - 1) {
val part = pathParts[i]
current = when {
part.matches(Regex("\\d+")) -> current.get(part.toInt())
else -> current.get(part)
} ?: throw JsonException("Path not found: ${pathParts.subList(0, i + 1).joinToString("/")}")
}
return current
}
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
val mapperBuilder = Jackson3ApiJavaHelper.rebuild(objectMapper)
mapperBuilder.addModule(c.getJackson3Module())
this.objectMapper = mapperBuilder.build()
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JSONA.kt
* LastUpdate 2026-02-05 10:34:30
* LastUpdate 2026-02-26 14:14:18
* UpdateUser MingLiPro
*/
@@ -28,6 +28,7 @@ import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import java.io.File
import java.io.InputStream
import java.io.OutputStream
@@ -71,7 +72,7 @@ object JSONA {
* @param T 继承自JsonApi的具体实现类
*/
inline fun <reified T : JsonApi> setJsonApi() {
setJsonApi(T::class.java.newInstance() as JsonApi)
setJsonApi(T::class.java.getConstructor().newInstance() as JsonApi)
}
/**
@@ -127,14 +128,6 @@ object JSONA {
@JvmStatic
fun format(obj: Any): String = getJsonApi().format(obj)
/**
* 将对象格式化为带Unicode转义的JSON字符串
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的JSON字符串
*/
@JvmStatic
fun formatUnicode(obj: Any): String = getJsonApi().formatPrettyUnicode(obj)
/**
* 从文件路径解析JSON为指定类型的对象
@@ -291,24 +284,6 @@ object JSONA {
@JvmStatic
fun formatPrettyBytes(obj: Any): ByteArray = getJsonApi().formatPrettyBytes(obj)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的美化JSON字符串
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any): String = getJsonApi().formatPrettyUnicode(obj)
/**
* 将对象格式化为带Unicode转义的美化JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的美化JSON字节数组
*/
@JvmStatic
fun formatPrettyUnicodeBytes(obj: Any): ByteArray = getJsonApi().formatPrettyUnicodeBytes(obj)
/**
* 将对象格式化为美化格式的JSON字符串并写入文件
*
@@ -345,41 +320,6 @@ object JSONA {
@JvmStatic
fun formatPretty(obj: Any, stream: OutputStream) = getJsonApi().formatPretty(obj, stream)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: String) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: Path) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: File) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, stream: OutputStream) = getJsonApi().formatPrettyUnicode(obj, stream)
/**
* 将对象格式化为JSON字节数组
@@ -390,14 +330,6 @@ object JSONA {
@JvmStatic
fun formatBytes(obj: Any): ByteArray = getJsonApi().formatBytes(obj)
/**
* 将对象格式化为带Unicode转义的JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的JSON字节数组
*/
@JvmStatic
fun formatUnicodeBytes(obj: Any): ByteArray = getJsonApi().formatUnicodeBytes(obj)
/**
* 将对象格式化为JSON字符串并写入文件
@@ -435,41 +367,6 @@ object JSONA {
@JvmStatic
fun format(obj: Any, stream: OutputStream) = getJsonApi().format(obj, stream)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun formatUnicode(obj: Any, file: String) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun formatUnicode(obj: Any, file: Path) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun formatUnicode(obj: Any, file: File) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@JvmStatic
fun formatUnicode(obj: Any, stream: OutputStream) = getJsonApi().formatUnicode(obj, stream)
/**
* 将JSON字符串解析为指定元素类型的List集合
@@ -627,8 +524,7 @@ object JSONA {
*
* @param T 继承自BaseJsonConverter的具体实现类
*/
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() =
addJsonConverter(T::class.java.newInstance())
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() = addJsonConverter(getJsonConverter<T>())
inline fun <reified T> String.parseJson() = parse<T>(this)
@@ -639,6 +535,9 @@ object JSONA {
fun Any.toJson() = format(this)
@JvmStatic
fun jacksonKotlinObjectMapper(): ObjectMapper = ObjectMapper().jacksonKotlinObjectMapper()
@JvmStatic
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-02-05 14:41:27
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -32,6 +32,7 @@ import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJacksonModule
/**
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
@@ -110,7 +111,7 @@ class JacksonJsonApi : JsonApi {
}
}
override fun formatUnicode(obj: Any): String {
fun formatUnicode(obj: Any): String {
return try {
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
} catch (e: Exception) {
@@ -135,7 +136,7 @@ class JacksonJsonApi : JsonApi {
}
}
override fun formatPrettyUnicode(obj: Any): String {
fun formatPrettyUnicode(obj: Any): String {
return try {
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
.writeValueAsString(obj)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonApi.kt
* LastUpdate 2026-02-04 21:00:48
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -25,6 +25,7 @@ package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
@@ -111,7 +112,7 @@ interface JsonApi {
* @return 解析后的Map集合
*/
inline fun <reified K, reified V> JsonApi.parseMap(
json: String
json: String,
): MutableMap<K, V> = parseMap(json, K::class.java, V::class.java)
@@ -133,7 +134,7 @@ interface JsonApi {
*/
@JvmStatic
inline fun <reified T : BaseJsonConverter<*, *>> JsonApi.addJsonConverter() {
addJsonConverter(T::class.java.newInstance())
addJsonConverter(getJsonConverter<T>())
}
}
@@ -166,8 +167,6 @@ interface JsonApi {
*/
fun format(obj: Any): String
fun formatUnicode(obj: Any): String
/**
* 从文件路径读取JSON并解析为指定类型对象
*
@@ -333,7 +332,7 @@ interface JsonApi {
* @return 解析后的对象实例或默认值
**/
fun <T> parse(
json: String, type: JsonTypeReference<T>, defaultValue: T
json: String, type: JsonTypeReference<T>, defaultValue: T,
): T {
return try {
parse<T>(json, type)
@@ -354,12 +353,6 @@ interface JsonApi {
return formatPretty(obj)!!.toByteArray()
}
fun formatPrettyUnicode(obj: Any): String
fun formatPrettyUnicodeBytes(obj: Any): ByteArray {
return formatPrettyUnicode(obj)!!.toByteArray()
}
fun formatPretty(obj: Any, file: String) {
formatPretty(obj, Paths.get(file))
}
@@ -378,30 +371,8 @@ interface JsonApi {
stream.write(formatPrettyBytes(obj))
}
fun formatPrettyUnicode(obj: Any, file: String) {
formatPrettyUnicode(obj, Paths.get(file))
}
fun formatPrettyUnicode(obj: Any, file: Path) {
formatPrettyUnicode(obj, file.toFile())
}
fun formatPrettyUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatPrettyUnicode(obj, fos)
}
}
fun formatPrettyUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
fun formatBytes(obj: Any): ByteArray {
return format(obj)!!.toByteArray()
}
fun formatUnicodeBytes(obj: Any): ByteArray {
return formatUnicode(obj)!!.toByteArray()
return format(obj).toByteArray()
}
fun format(obj: Any, file: String) {
@@ -422,23 +393,6 @@ interface JsonApi {
stream.write(formatPrettyBytes(obj))
}
fun formatUnicode(obj: Any, file: String) {
formatUnicode(obj, Paths.get(file))
}
fun formatUnicode(obj: Any, file: Path) {
formatUnicode(obj, file.toFile())
}
fun formatUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatUnicode(obj, fos)
}
}
fun formatUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
/**
* 将JSON字符串解析为指定元素类型的List集合
@@ -463,7 +417,7 @@ interface JsonApi {
* @return 解析后的Map集合
</V></K> */
fun <K, V> parseMap(
json: String, keyType: Class<K>, valueType: Class<V>
json: String, keyType: Class<K>, valueType: Class<V>,
): MutableMap<K, V> {
val mapType: JsonTypeReference<MutableMap<K, V>> = object : JsonTypeReference<MutableMap<K, V>>() {}
return parse<MutableMap<K, V>>(json, mapType)
@@ -16,16 +16,16 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile TypeReference.kt
* LastUpdate 2026-02-04 21:00:48
* LastUpdate 2026-02-26 14:11:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api.type
import com.mingliqiye.utils.string.join
import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
class TypeReference(
val rawClass: Type,
@@ -40,23 +40,37 @@ class TypeReference(
override fun getOwnerType(): Type? = null
override fun toString(): String = "${getRawString(rawType)}<${
",".join(typeArguments, TypeReference::getRawString)
override fun toString(): String = "${getRawString(rawClass)}<${
",".join(typeArguments) { getRawString(it) }
}>"
companion object {
fun getRawString(s: Any): String {
if (s is Class<*>) {
return s.name
fun getRawString(type: Type): String {
return when (type) {
is Class<*> -> type.name
is WildcardType -> {
val upperBounds = type.upperBounds
val lowerBounds = type.lowerBounds
when {
upperBounds.isNotEmpty() && upperBounds[0] != Any::class.java -> {
"? extends ${getRawString(upperBounds[0])}"
}
lowerBounds.isNotEmpty() -> {
"? super ${getRawString(lowerBounds[0])}"
}
else -> "?"
}
}
is ParameterizedType -> {
of(type).toString()
}
else -> type.typeName
}
if (s is WildcardTypeImpl) {
return getRawString(s.upperBounds[0])
}
if (s is ParameterizedType) {
return of(s).toString()
}
return s.toString()
}
inline fun <reified T> of(): TypeReference {
@@ -64,13 +78,17 @@ class TypeReference(
}
fun of(type: Type): TypeReference {
if (type is Class<*>) {
return TypeReference(type)
return when (type) {
is Class<*> -> TypeReference(type)
is ParameterizedType -> TypeReference(type.rawType, *type.actualTypeArguments)
is WildcardType -> {
// 处理通配符类型,返回上界类型
val upperBound = type.upperBounds.firstOrNull() ?: Any::class.java
TypeReference(upperBound)
}
else -> throw IllegalStateException("无法获取类型: $type")
}
if (type is ParameterizedType) {
return TypeReference(type.rawType, *type.actualTypeArguments)
}
throw IllegalStateException("无法获取类型: $type")
}
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AnnotationGetter.kt
* LastUpdate 2026-02-06 16:57:45
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -73,6 +73,7 @@ interface AnnotationGetter {
* @param clazz 目标注解类型的Class对象。
* @return 如果annotation的类型与clazz一致,则返回annotation转换为T类型的实例;否则返回null。
*/
@Suppress("UNCHECKED_CAST")
override fun <T : Annotation> get(clazz: Class<T>): T? =
if (annotation.javaClass == clazz) annotation as T else null
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonConverter.kt
* LastUpdate 2026-02-08 01:22:35
* LastUpdate 2026-02-26 15:59:35
* UpdateUser MingLiPro
*/
@@ -31,4 +31,4 @@ package com.mingliqiye.utils.json.converters.base
* @param F 源类型,表示需要被转换的数据类型。
* @param T 目标类型,表示转换后的数据类型。
*/
interface BaseJsonConverter<F, T> : JackSonJsonConverter<F, T>
interface BaseJsonConverter<F, T> : JsonConverter<F, T>
@@ -0,0 +1,62 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackJson3Deserializer.kt
* LastUpdate 2026-02-26 13:02:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import tools.jackson.core.JsonParser
import tools.jackson.core.JsonToken
import tools.jackson.databind.BeanProperty
import tools.jackson.databind.DeserializationContext
import tools.jackson.databind.ValueDeserializer
class JackJson3Deserializer<F, T>(
val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>
) : ValueDeserializer<F>() {
override fun deserialize(
p: JsonParser,
ctxt: DeserializationContext?
): F? {
if (p.currentToken() == JsonToken.VALUE_NULL) return null
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
}
/**
* 上下文感知方法:设置当前属性信息。
*
* @param ctxt 反序列化上下文,可选参数。
* @param property 当前属性信息。
* @return 返回当前反序列化器实例。
*/
override fun createContextual(
ctxt: DeserializationContext?,
property: BeanProperty?
): JackJson3Deserializer<F, T> {
return JackJson3Deserializer(property, jsonConverter)
}
}
@@ -0,0 +1,66 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackJson3Serializer.kt
* LastUpdate 2026-02-26 13:04:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import tools.jackson.databind.BeanProperty
import tools.jackson.databind.SerializationContext
import tools.jackson.databind.ValueSerializer
import java.math.BigDecimal
import java.math.BigInteger
class JackJson3Serializer<F, T>(
val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>
) : ValueSerializer<F>() {
/**
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
*
* @param value 源对象,可能为 null。
* @param gen JSON 生成器,用于写入 JSON 数据。
* @param provider 序列化提供者,可选参数。
*/
override fun serialize(value: F, gen: tools.jackson.core.JsonGenerator, ctxt: SerializationContext) {
val data: T? = jsonConverter.convert(value, object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
when (data) {
null -> gen.writeNull()
is String -> gen.writeString(data)
is Long -> gen.writeNumber(data)
is Short -> gen.writeNumber(data)
is Byte -> gen.writeNumber(data.toShort())
is Int -> gen.writeNumber(data)
is BigDecimal -> gen.writeNumber(data)
is BigInteger -> gen.writeNumber(data)
is Float -> gen.writeNumber(data)
is Double -> gen.writeNumber(data)
is Boolean -> gen.writeBoolean(data)
else -> throw IllegalArgumentException("not sport data type ${data.javaClass} $data")
}
}
override fun createContextual(ctxt: SerializationContext?, property: BeanProperty?): ValueSerializer<*> {
return JackJson3Serializer(property, jsonConverter)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackJsonSerializer.kt
* LastUpdate 2026-02-08 02:27:52
* LastUpdate 2026-02-26 12:55:57
* UpdateUser MingLiPro
*/
@@ -1,57 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackSonJsonConverter.kt
* LastUpdate 2026-02-08 02:28:49
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
interface JackSonJsonConverter<F, T> : JsonConverter<F, T> {
companion object {
/**
* 扩展ObjectMapper,用于注册指定类型的模块。
*
* 此函数通过反射创建指定类型的实例,并调用其getJacksonModule方法来获取Jackson模块,
* 然后将该模块注册到当前ObjectMapper实例中。
*
* @param T 必须继承自BaseJsonConverter的泛型类型。
* @return 返回注册了模块后的ObjectMapper实例。
*/
inline fun <reified T : BaseJsonConverter<*, *>> ObjectMapper.addJsonConverter(): ObjectMapper =
this.registerModule(getJsonConverter<T>().getJacksonModule())
@JvmStatic
fun <T : BaseJsonConverter<*, *>> ObjectMapper.addJsonConverter(clazz: Class<T>): ObjectMapper =
this.registerModule(getJsonConverter(clazz).getJacksonModule())
}
/**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
*
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
*/
fun getJacksonModule(): SimpleModule =
SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJsonSerializer(null, this))
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this))
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonConverterUtils.kt
* LastUpdate 2026-02-07 22:33:09
* LastUpdate 2026-02-26 16:01:49
* UpdateUser MingLiPro
*/
@file:JvmName("JsonConverterUtils")
@@ -49,6 +49,7 @@ fun getClass(type: Type?): Class<*>? {
inline fun <reified T : JsonConverter<*, *>> getJsonConverter(): T = getJsonConverter(T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T : JsonConverter<*, *>> getJsonConverter(clazz: Class<T>): T {
try {
return clazz.getDeclaredMethod(
@@ -59,3 +60,25 @@ fun <T : JsonConverter<*, *>> getJsonConverter(clazz: Class<T>): T {
throw e
}
}
fun <T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(clazz: Class<T>): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(clazz).getJacksonModule())
@JvmName("inline_addJsonConverter")
inline fun <reified T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(T::class.java).getJacksonModule())
/**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
*
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
*/
fun <F, T> JsonConverter<F, T>.getJacksonModule(): com.fasterxml.jackson.databind.module.SimpleModule =
com.fasterxml.jackson.databind.module.SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJsonSerializer(null, this))
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this))
fun <F, T> JsonConverter<F, T>.getJackson3Module(): tools.jackson.databind.module.SimpleModule =
tools.jackson.databind.module.SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJson3Serializer(null, this))
.addDeserializer(getFromClass(), JackJson3Deserializer(null, this))