no message

This commit is contained in:
2026-02-05 11:42:52 +08:00
parent f2ee83ca64
commit a5a532bc82
90 changed files with 7945 additions and 2458 deletions
@@ -1,231 +0,0 @@
/*
* Copyright 2025 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 GsonJsonApi.kt
* LastUpdate 2025-09-15 22:07:43
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
import com.google.gson.*
import com.mingliqiye.utils.json.converters.JsonConverter
import com.mingliqiye.utils.json.converters.JsonStringConverter
class GsonJsonApi : JsonApi {
private var gsonUnicode: Gson
private var gsonPretty: Gson
private var gsonPrettyUnicode: Gson
private var gson: Gson
constructor() {
gson = GsonBuilder()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
gsonUnicode = GsonBuilder()
.disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
gsonPretty = GsonBuilder()
.setPrettyPrinting()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
gsonPrettyUnicode = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
}
constructor(gson: Gson) {
this.gson = gson
.newBuilder()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
this.gsonUnicode = gson
.newBuilder()
.disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
this.gsonPretty = gson
.newBuilder()
.setPrettyPrinting()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
this.gsonPrettyUnicode = gson
.newBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create()
}
override fun <T> parse(json: String, clazz: Class<T>): T {
return gson.fromJson(json, clazz)
}
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
return gson.fromJson(json, type.type)
}
override fun format(obj: Any): String {
return gson.toJson(obj)
}
override fun formatUnicode(obj: Any): String {
return gsonUnicode.toJson(obj)
}
override fun formatPretty(obj: Any): String {
return gsonPretty.toJson(obj)
}
override fun formatPrettyUnicode(obj: Any): String {
return gsonPrettyUnicode.toJson(obj)
}
override fun isValidJson(json: String): Boolean {
return try {
JsonParser.parseString(json)
true
} catch (e: JsonSyntaxException) {
false
} catch (e: Exception) {
false
}
}
override fun merge(vararg jsons: String): String {
val merged = JsonObject()
for (json in jsons) {
if (json.isNullOrEmpty()) {
continue
}
try {
val obj = JsonParser.parseString(json).asJsonObject
for (key in obj.keySet()) {
merged.add(key, obj.get(key))
}
} catch (e: Exception) {
// 忽略无效的 JSON 字符串
}
}
return gson.toJson(merged)
}
override fun getNodeValue(json: String, path: String): String? {
return try {
var element = JsonParser.parseString(json)
val paths = path.split("\\.".toRegex()).toTypedArray()
var current = element
for (p in paths) {
if (current.isJsonObject) {
current = current.asJsonObject.get(p)
} else {
return null
}
if (current == null) {
return null
}
}
if (current.isJsonPrimitive) current.asString else current.toString()
} catch (e: Exception) {
null
}
}
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
return try {
val obj = JsonParser.parseString(json).asJsonObject
val paths = path.split("\\.".toRegex()).toTypedArray()
var current = obj
// 导航到倒数第二层
for (i in 0 until paths.size - 1) {
val p = paths[i]
if (!current.has(p) || !current.get(p).isJsonObject) {
current.add(p, JsonObject())
}
current = current.getAsJsonObject(p)
}
// 设置最后一层的值
val lastPath = paths[paths.size - 1]
val element = gson.toJsonTree(newValue)
current.add(lastPath, element)
gson.toJson(obj)
} catch (e: Exception) {
json
}
}
override fun <T, D> convert(source: T, destinationClass: Class<D>): D {
val json = gson.toJson(source)
return gson.fromJson(json, destinationClass)
}
override fun <T, D> convert(source: T, destinationType: JsonTypeReference<D>): D {
val json = gson.toJson(source)
return gson.fromJson(json, destinationType.type)
}
override fun addJsonConverter(c: JsonConverter<*, *>) {
c.getStringConverter()?.let {
gson = gson
.newBuilder()
.registerTypeAdapter(
it.tClass,
it.gsonJsonStringConverterAdapter
)
.create()
gsonUnicode = gsonUnicode
.newBuilder()
.registerTypeAdapter(
it.tClass,
it.gsonJsonStringConverterAdapter
)
.create()
gsonPretty = gsonPretty
.newBuilder()
.registerTypeAdapter(
it.tClass,
it.gsonJsonStringConverterAdapter
)
.create()
gsonPrettyUnicode = gsonPrettyUnicode
.newBuilder()
.registerTypeAdapter(
it.tClass,
it.gsonJsonStringConverterAdapter
)
.create()
}
}
override fun addJsonStringConverter(c: JsonStringConverter<*>) {
addJsonConverter(c)
}
}
@@ -1,32 +0,0 @@
/*
* Copyright 2025 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 JsonException.kt
* LastUpdate 2025-09-15 22:32:50
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
class JsonException : RuntimeException {
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
constructor(cause: Throwable) : this(cause.message ?: "", cause)
}
@@ -0,0 +1,644 @@
/*
* 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 JSONA.kt
* LastUpdate 2026-02-05 10:34:30
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.kotlinModule
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 java.io.File
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Path
/**
* JSON工具类,提供静态方法访问JSON API功能
*/
object JSONA {
@JvmStatic
private var jsonApi: JsonApi? = null
/**
* 获取JSON API实例
*
* @return JSON API实例
* @throws NullPointerException 当JSON API未初始化时抛出异常
*/
@Throws(NullPointerException::class)
@JvmStatic
fun getJsonApi(): JsonApi {
if (jsonApi == null) {
throw NullPointerException("jsonApi is null plase setJsonApi first")
}
return jsonApi!!
}
/**
* 设置JSON API实例
*
* @param jsa JSON API实例
*/
@JvmStatic
fun setJsonApi(jsa: JsonApi) {
jsonApi = jsa
}
/**
* 使用反射创建并设置指定类型的JSON API实例
*
* @param T 继承自JsonApi的具体实现类
*/
inline fun <reified T : JsonApi> setJsonApi() {
setJsonApi(T::class.java.newInstance() as JsonApi)
}
/**
* 将JSON字符串解析为指定类型的对象
*
* @param json 待解析的JSON字符串
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parse(json: String, clazz: Class<T>): T = getJsonApi().parse(json, clazz)
/**
* 将JSON字符串解析为指定泛型类型对象
*
* @param json 待解析的JSON字符串
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
inline fun <reified T> parse(json: String): T {
return getJsonApi().parse(json, (object : JsonTypeReference<T>() {}))
}
/**
* 将字节数组形式的JSON解析为指定泛型类型对象
*
* @param json 待解析的JSON字节数组
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
inline fun <reified T> parse(json: ByteArray): T = getJsonApi().parse(json, object : JsonTypeReference<T>() {})
/**
* 将JSON字符串解析为指定泛型类型对象
*
* @param json 待解析的JSON字符串
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parse(json: String, type: JsonTypeReference<T>): T = getJsonApi().parse(json, type)
/**
* 将对象格式化为JSON字符串
*
* @param obj 待格式化的对象
* @return 格式化后的JSON字符串
*/
@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为指定类型的对象
*
* @param path 文件路径
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(path: String, clazz: Class<T>): T = getJsonApi().parseFrom(path, clazz)
/**
* 从Path对象解析JSON为指定类型的对象
*
* @param path Path对象
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(path: Path, clazz: Class<T>): T = getJsonApi().parseFrom(path, clazz)
/**
* 从File对象解析JSON为指定类型的对象
*
* @param file File对象
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(file: File, clazz: Class<T>): T = getJsonApi().parseFrom(file, clazz)
/**
* 从InputStream解析JSON为指定类型的对象
*
* @param inputStream InputStream对象
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(inputStream: InputStream, clazz: Class<T>): T = getJsonApi().parseFrom(inputStream, clazz)
/**
* 从文件路径解析JSON为指定泛型类型对象
*
* @param path 文件路径
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(path: String, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(path, type)
/**
* 从Path对象解析JSON为指定泛型类型对象
*
* @param path Path对象
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(path: Path, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(path, type)
/**
* 从File对象解析JSON为指定泛型类型对象
*
* @param file File对象
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(file: File, type: JsonTypeReference<T>): T = getJsonApi().parseFrom(file, type)
/**
* 从InputStream解析JSON为指定泛型类型对象
*
* @param inputStream InputStream对象
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parseFrom(inputStream: InputStream, type: JsonTypeReference<T>): T =
getJsonApi().parseFrom(inputStream, type)
/**
* 将字节数组形式的JSON解析为指定类型的对象
*
* @param json 待解析的JSON字节数组
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parse(json: ByteArray, clazz: Class<T>): T = getJsonApi().parse(json, clazz)
/**
* 将字节数组形式的JSON解析为指定泛型类型对象
*
* @param json 待解析的JSON字节数组
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
@JvmStatic
fun <T> parse(json: ByteArray, type: JsonTypeReference<T>): T = getJsonApi().parse(json, type)
/**
* 将JSON字符串解析为指定类型的对象,解析失败时返回默认值
*
* @param json 待解析的JSON字符串
* @param clazz 目标对象的Class类型
* @param defaultValue 解析失败时返回的默认值
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例或默认值
*/
@JvmStatic
fun <T> parse(json: String, clazz: Class<T>, defaultValue: T): T = getJsonApi().parse(json, clazz, defaultValue)
/**
* 将JSON字符串解析为指定泛型类型对象,解析失败时返回默认值
*
* @param json 待解析的JSON字符串
* @param type 目标对象的Type类型(支持泛型)
* @param defaultValue 解析失败时返回的默认值
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例或默认值
*/
@JvmStatic
fun <T> parse(
json: String, type: JsonTypeReference<T>, defaultValue: T
): T = getJsonApi().parse(json, type, defaultValue)
/**
* 将对象格式化为美化格式的JSON字符串(带缩进和换行)
*
* @param obj 待格式化的对象
* @return 格式化后的美化JSON字符串
*/
@JvmStatic
fun formatPretty(obj: Any): String = getJsonApi().formatPretty(obj)
/**
* 将对象格式化为美化格式的JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的美化JSON字节数组
*/
@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字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun formatPretty(obj: Any, file: String) = getJsonApi().formatPretty(obj, file)
/**
* 将对象格式化为美化格式的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun formatPretty(obj: Any, file: Path) = getJsonApi().formatPretty(obj, file)
/**
* 将对象格式化为美化格式的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun formatPretty(obj: Any, file: File) = getJsonApi().formatPretty(obj, file)
/**
* 将对象格式化为美化格式的JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@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字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的JSON字节数组
*/
@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字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun format(obj: Any, file: String) = getJsonApi().format(obj, file)
/**
* 将对象格式化为JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun format(obj: Any, file: Path) = getJsonApi().format(obj, file)
/**
* 将对象格式化为JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun format(obj: Any, file: File) = getJsonApi().format(obj, file)
/**
* 将对象格式化为JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@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集合
*
* @param json 待解析的JSON字符串
* @param elementType List中元素的类型
* @param <T> 泛型参数,表示List中元素的类型
* @return 解析后的List集合
*/
@JvmStatic
fun <T> parseList(json: String, elementType: Class<T>): List<T> = parse(json, listType(elementType))
/**
* 将JSON字符串解析为指定元素类型的List集合
*
* @param json 待解析的JSON字符串
* @param <T> 泛型参数,表示List中元素的类型
* @return 解析后的List集合
*/
@JvmStatic
inline fun <reified T> parseList(json: String): List<T> = parse(json, listType(T::class.java))
/**
* 将JSON字符串解析为指定键值类型的Map集合
*
* @param json 待解析的JSON字符串
* @param keyType Map中键的类型
* @param valueType Map中值的类型
* @param <K> 泛型参数,表示Map中键的类型
* @param <V> 泛型参数,表示Map中值的类型
* @return 解析后的Map集合
*/
@JvmStatic
fun <K, V> parseMap(
json: String, keyType: Class<K>, valueType: Class<V>
): MutableMap<K, V> = getJsonApi().parseMap(json, keyType, valueType)
/**
* 将JSON字符串解析为指定键值类型的Map集合
*
* @param json 待解析的JSON字符串
* @param <K> 泛型参数,表示Map中键的类型
* @param <V> 泛型参数,表示Map中值的类型
* @return 解析后的Map集合
*/
@JvmStatic
inline fun <reified K, reified V> parseMap(
json: String
): MutableMap<K, V> = getJsonApi().parseMap(json, K::class.java, V::class.java)
/**
* 验证字符串是否为有效的JSON格式
*
* @param json 待验证的字符串
* @return 如果是有效的JSON格式返回true,否则返回false
*/
@JvmStatic
fun isValidJson(json: String): Boolean = getJsonApi().isValidJson(json)
/**
* 将对象转换为JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的JSON字节数组
*/
@JvmStatic
fun toBytes(obj: Any): ByteArray = getJsonApi().toBytes(obj)
/**
* 将对象转换为美化格式的JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的美化格式JSON字节数组
*/
@JvmStatic
fun toBytesPretty(obj: Any): ByteArray = getJsonApi().toBytesPretty(obj)
/**
* 合并多个JSON字符串为一个JSON对象
*
* @param jsons 待合并的JSON字符串数组
* @return 合并后的JSON字符串
*/
@JvmStatic
fun merge(vararg jsons: String): String = getJsonApi().merge(*jsons)
/**
* 获取JSON字符串中指定路径节点的值
*
* @param json JSON字符串
* @param path 节点路径(如:"user.name")
* @return 节点值的字符串表示
*/
@JvmStatic
fun getNodeValue(json: String, path: String): String? = getJsonApi().getNodeValue(json, path)
/**
* 更新JSON字符串中指定路径节点的值
*
* @param json 原始JSON字符串
* @param path 节点路径(如:"user.name")
* @param newValue 新的节点值
* @return 更新后的JSON字符串
*/
@JvmStatic
fun updateNodeValue(json: String, path: String, newValue: Any): String =
getJsonApi().updateNodeValue(json, path, newValue)
/**
* 将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationClass 目标对象的Class类型
* @return 转换后的目标类型对象
*/
@JvmStatic
fun <D> convert(source: Any, destinationClass: Class<D>): D = getJsonApi().convert(source, destinationClass)
/**
* 使用内联函数和reified类型参数将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型(通过reified类型参数推断)
* @param source 需要转换的源对象
* @return 转换后的目标类型对象
*/
@JvmStatic
inline fun <reified D> convert(source: Any): D = getJsonApi().convert(source, object : JsonTypeReference<D>() {})
/**
* 将源对象转换为目标类型的对象,使用JsonTypeReference指定目标类型
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationType 目标对象的JsonTypeReference类型引用
* @return 转换后的目标类型对象
*/
@JvmStatic
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D =
getJsonApi().convert(source, destinationType)
/**
* 添加JSON转换器到API中
*
* @param c 需要添加的JSON转换器实例
*/
@JvmStatic
fun addJsonConverter(c: BaseJsonConverter<*, *>) = getJsonApi().addJsonConverter(c)
/**
* 使用反射创建并添加指定类型的JSON转换器到API中
*
* @param T 继承自BaseJsonConverter的具体实现类
*/
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() =
addJsonConverter(T::class.java.newInstance())
inline fun <reified T> String.parseJson() = parse<T>(this)
inline fun <reified T> ByteArray.parseJson() = parse<T>(this)
inline fun <reified T> InputStream.parseJson() = this.use { parse<T>(readBytes()) }
inline fun <reified T> File.parseJson() = this.inputStream().parseJson<T>()
inline fun <reified T> Path.parseJson() = this.toFile().inputStream().parseJson<T>()
fun Any.toJson() = format(this)
fun jacksonKotlinObjectMapper(): ObjectMapper = ObjectMapper().jacksonKotlinObjectMapper()
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,11 +16,11 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2025-09-15 22:07:43
* LastUpdate 2026-02-05 10:31:14
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonProcessingException
@@ -28,9 +28,10 @@ import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectReader
import com.fasterxml.jackson.databind.node.ObjectNode
import com.mingliqiye.utils.json.converters.JsonConverter
import com.mingliqiye.utils.json.converters.JsonStringConverter
import java.io.IOException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.exception.JsonException
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
/**
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
@@ -52,7 +53,7 @@ class JacksonJsonApi : JsonApi {
* @param objectMapper 自定义的ObjectMapper实例
*/
constructor(objectMapper: ObjectMapper) {
this.objectMapper = objectMapper.copy()
this.objectMapper = objectMapper
}
/**
@@ -62,12 +63,12 @@ class JacksonJsonApi : JsonApi {
* @param clazz 目标对象类型
* @param <T> 泛型参数,表示目标对象类型
* @return 解析后的对象
* @throws JsonException 当解析失败时抛出异常
* @throws com.mingliqiye.utils.json.api.exception.JsonException 当解析失败时抛出异常
*/
override fun <T> parse(json: String, clazz: Class<T>): T {
return try {
objectMapper.readValue(json, clazz)
} catch (e: IOException) {
} catch (e: Exception) {
throw JsonException("Failed to parse JSON string", e)
}
}
@@ -87,7 +88,7 @@ class JacksonJsonApi : JsonApi {
objectMapper.constructType(type.type)
)
reader.readValue(json)
} catch (e: IOException) {
} catch (e: Exception) {
throw JsonException("Failed to parse JSON string", e)
}
}
@@ -102,21 +103,17 @@ class JacksonJsonApi : JsonApi {
override fun format(obj: Any): String {
return try {
objectMapper.writeValueAsString(obj)
} catch (e: JsonProcessingException) {
} catch (e: Exception) {
throw JsonException(
"Failed to format object to JSON string",
e
"Failed to format object to JSON string", e
)
}
}
override fun formatUnicode(obj: Any): String {
return try {
objectMapper
.writer()
.with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
.writeValueAsString(obj)
} catch (e: JsonProcessingException) {
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException(e)
}
}
@@ -130,27 +127,21 @@ class JacksonJsonApi : JsonApi {
*/
override fun formatPretty(obj: Any): String {
return try {
objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(obj)
} catch (e: JsonProcessingException) {
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException(
"Failed to format object to pretty JSON string",
e
"Failed to format object to pretty JSON string", e
)
}
}
override fun formatPrettyUnicode(obj: Any): String {
return try {
objectMapper
.writerWithDefaultPrettyPrinter()
.with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
.writeValueAsString(obj)
} catch (e: JsonProcessingException) {
} catch (e: Exception) {
throw JsonException(
"Failed to format object to pretty JSON string",
e
"Failed to format object to pretty JSON string", e
)
}
}
@@ -186,8 +177,7 @@ class JacksonJsonApi : JsonApi {
if (node.isObject) {
result.setAll<JsonNode>(node as ObjectNode)
}
} catch (e: IOException) {
// 忽略无效的JSON字符串
} catch (e: Exception) {
}
}
return try {
@@ -213,7 +203,7 @@ class JacksonJsonApi : JsonApi {
node = node.get(p)
}
node.asText()
} catch (e: IOException) {
} catch (e: Exception) {
throw JsonException("Failed to get node value", e)
}
}
@@ -247,15 +237,14 @@ class JacksonJsonApi : JsonApi {
if (current is ObjectNode) {
val parent: ObjectNode = current
parent.set<JsonNode>(
paths[paths.size - 1],
objectMapper.valueToTree(newValue)
paths[paths.size - 1], objectMapper.valueToTree(newValue)
)
}
objectMapper.writeValueAsString(objectNode)
}
json
} catch (e: IOException) {
} catch (e: Exception) {
throw JsonException("Failed to update node value", e)
}
}
@@ -269,8 +258,12 @@ class JacksonJsonApi : JsonApi {
* @param <D> 目标对象类型
* @return 转换后的对象
*/
override fun <T, D> convert(source: T, destinationClass: Class<D>): D {
return objectMapper.convertValue(source, destinationClass)
override fun <D> convert(source: Any, destinationClass: Class<D>): D {
try {
return objectMapper.convertValue(source, destinationClass)
} catch (e: Exception) {
throw JsonException("Failed to update node value", e)
}
}
/**
@@ -282,20 +275,21 @@ class JacksonJsonApi : JsonApi {
* @param <D> 目标对象类型
* @return 转换后的对象
*/
override fun <T, D> convert(source: T, destinationType: JsonTypeReference<D>): D {
return objectMapper.convertValue(
source,
objectMapper.constructType(destinationType.type)
)
}
override fun addJsonConverter(c: JsonConverter<*, *>) {
c.getStringConverter()?.let {
objectMapper.registerModule(it.jacksonJsonStringConverterAdapter.jacksonModule)
override fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D {
try {
return objectMapper.convertValue(
source, objectMapper.constructType(destinationType.type)
)
} catch (e: Exception) {
throw JsonException("Failed to update node value", e)
}
}
override fun addJsonStringConverter(c: JsonStringConverter<*>) {
addJsonConverter(c)
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
try {
objectMapper.registerModule(c.getJacksonModule())
} catch (e: Exception) {
throw JsonException("Failed to update node value", e)
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,24 +16,128 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonApi.kt
* LastUpdate 2025-09-15 22:32:50
* LastUpdate 2026-02-04 21:00:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.json.converters.JsonConverter
import com.mingliqiye.utils.json.converters.JsonStringConverter
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 java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* JSON处理接口,提供JSON字符串与Java对象之间的相互转换功能
*/
interface JsonApi {
companion object {
/**
* 将JSON字符串解析为指定泛型类型对象
*
* @param json 待解析的JSON字符串
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parse(json: String): T = parse(json, object : JsonTypeReference<T>() {})
/**
* 将JSON字节数组解析为指定泛型类型对象
*
* @param json 待解析的JSON字节数组
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parse(json: ByteArray): T = parse(json, object : JsonTypeReference<T>() {})
/**
* 将JSON字符串解析为指定泛型类型对象,解析失败时返回默认值
*
* @param json 待解析的JSON字符串
* @param defect 解析失败时返回的默认值
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例或默认值
*/
inline fun <reified T> JsonApi.parse(json: String, defect: T): T =
parse(json, object : JsonTypeReference<T>() {}, defect)
/**
* 从文件路径读取JSON并解析为指定泛型类型对象
*
* @param path 文件路径
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parseFrom(path: String): T = parseFrom(path, object : JsonTypeReference<T>() {})
/**
* 从文件读取JSON并解析为指定泛型类型对象
*
* @param path 文件对象
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parseFrom(path: File): T = parseFrom(path, object : JsonTypeReference<T>() {})
/**
* 从输入流读取JSON并解析为指定泛型类型对象
*
* @param path 输入流
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parseFrom(path: InputStream): T =
parseFrom(path, object : JsonTypeReference<T>() {})
/**
* 从路径读取JSON并解析为指定泛型类型对象
*
* @param path 路径对象
* @param T 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
inline fun <reified T> JsonApi.parseFrom(path: Path): T = parseFrom(path, object : JsonTypeReference<T>() {})
/**
* 将JSON字符串解析为指定键值类型的Map集合
*
* @param json 待解析的JSON字符串
* @param K 泛型参数,表示Map中键的类型
* @param V 泛型参数,表示Map中值的类型
* @return 解析后的Map集合
*/
inline fun <reified K, reified V> JsonApi.parseMap(
json: String
): MutableMap<K, V> = parseMap(json, K::class.java, V::class.java)
/**
* 使用内联函数和reified类型参数将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型(通过reified类型参数推断)
* @param source 需要转换的源对象
* @return 转换后的目标类型对象
*/
@JvmStatic
inline fun <reified D> JsonApi.convert(source: Any): D = convert(source, object : JsonTypeReference<D>() {})
/**
* 添加JSON转换器到API中
*
* @param T 需要添加的JSON转换器类
*/
@JvmStatic
inline fun <reified T : BaseJsonConverter<*, *>> JsonApi.addJsonConverter() {
addJsonConverter(T::class.java.newInstance())
}
}
/**
* 将JSON字符串解析为指定类型的对象
*
@@ -64,24 +168,52 @@ interface JsonApi {
fun formatUnicode(obj: Any): String
@Throws(IOException::class)
/**
* 从文件路径读取JSON并解析为指定类型对象
*
* @param path 文件路径
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(path: String, clazz: Class<T>): T {
return parseFrom(Paths.get(path), clazz)
}
@Throws(IOException::class)
/**
* 从路径读取JSON并解析为指定类型对象
*
* @param path 路径对象
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(path: Path, clazz: Class<T>): T {
return parseFrom(path.toFile(), clazz)
}
@Throws(IOException::class)
/**
* 从文件读取JSON并解析为指定类型对象
*
* @param file 文件对象
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(file: File, clazz: Class<T>): T {
Files.newInputStream(file.toPath()).use { inputStream ->
return parseFrom(inputStream, clazz)
}
}
@Throws(IOException::class)
/**
* 从输入流读取JSON并解析为指定类型对象
*
* @param inputStream 输入流
* @param clazz 目标对象的Class类型
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(inputStream: InputStream, clazz: Class<T>): T {
val bytes = ByteArray(1024)
ByteArrayOutputStream().use { bos ->
@@ -93,24 +225,52 @@ interface JsonApi {
}
}
@Throws(IOException::class)
/**
* 从文件路径读取JSON并解析为指定泛型类型对象
*
* @param path 文件路径
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(path: String, type: JsonTypeReference<T>): T {
return parseFrom(Paths.get(path), type)
}
@Throws(IOException::class)
/**
* 从路径读取JSON并解析为指定泛型类型对象
*
* @param path 路径对象
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(path: Path, type: JsonTypeReference<T>): T {
return parseFrom(path.toFile(), type)
}
@Throws(IOException::class)
/**
* 从文件读取JSON并解析为指定泛型类型对象
*
* @param file 文件对象
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(file: File, type: JsonTypeReference<T>): T {
Files.newInputStream(file.toPath()).use { inputStream ->
return parseFrom<T>(inputStream, type)
}
}
@Throws(IOException::class)
/**
* 从输入流读取JSON并解析为指定泛型类型对象
*
* @param inputStream 输入流
* @param type 目标对象的Type类型(支持泛型)
* @param <T> 泛型参数,表示目标对象的类型
* @return 解析后的对象实例
*/
fun <T> parseFrom(inputStream: InputStream, type: JsonTypeReference<T>): T {
val bytes = ByteArray(1024)
ByteArrayOutputStream().use { bos ->
@@ -156,10 +316,10 @@ interface JsonApi {
* @return 解析后的对象实例或默认值
</T> */
fun <T> parse(json: String, clazz: Class<T>, defaultValue: T): T {
try {
return parse(json, clazz)
return try {
parse(json, clazz)
} catch (e: Exception) {
return defaultValue
defaultValue
}
}
@@ -173,14 +333,12 @@ interface JsonApi {
* @return 解析后的对象实例或默认值
**/
fun <T> parse(
json: String,
type: JsonTypeReference<T>,
defaultValue: T
json: String, type: JsonTypeReference<T>, defaultValue: T
): T {
try {
return parse<T>(json, type)
return try {
parse<T>(json, type)
} catch (e: Exception) {
return defaultValue
defaultValue
}
}
@@ -202,46 +360,38 @@ interface JsonApi {
return formatPrettyUnicode(obj)!!.toByteArray()
}
@Throws(IOException::class)
fun formatPretty(obj: Any, file: String) {
formatPretty(obj, Paths.get(file))
}
@Throws(IOException::class)
fun formatPretty(obj: Any, file: Path) {
formatPretty(obj, file.toFile())
}
@Throws(IOException::class)
fun formatPretty(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatPretty(obj, fos)
}
}
@Throws(IOException::class)
fun formatPretty(obj: Any, stream: OutputStream) {
stream.write(formatPrettyBytes(obj))
}
@Throws(IOException::class)
fun formatPrettyUnicode(obj: Any, file: String) {
formatPrettyUnicode(obj, Paths.get(file))
}
@Throws(IOException::class)
fun formatPrettyUnicode(obj: Any, file: Path) {
formatPrettyUnicode(obj, file.toFile())
}
@Throws(IOException::class)
fun formatPrettyUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatPrettyUnicode(obj, fos)
}
}
@Throws(IOException::class)
fun formatPrettyUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
@@ -254,46 +404,38 @@ interface JsonApi {
return formatUnicode(obj)!!.toByteArray()
}
@Throws(IOException::class)
fun format(obj: Any, file: String) {
format(obj, Paths.get(file))
}
@Throws(IOException::class)
fun format(obj: Any, file: Path) {
format(obj, file.toFile())
}
@Throws(IOException::class)
fun format(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
format(obj, fos)
}
}
@Throws(IOException::class)
fun format(obj: Any, stream: OutputStream) {
stream.write(formatPrettyBytes(obj))
}
@Throws(IOException::class)
fun formatUnicode(obj: Any, file: String) {
formatUnicode(obj, Paths.get(file))
}
@Throws(IOException::class)
fun formatUnicode(obj: Any, file: Path) {
formatUnicode(obj, file.toFile())
}
@Throws(IOException::class)
fun formatUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatUnicode(obj, fos)
}
}
@Throws(IOException::class)
fun formatUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
@@ -321,9 +463,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)
@@ -384,10 +524,9 @@ interface JsonApi {
*/
fun updateNodeValue(json: String, path: String, newValue: Any): String
fun <T, D> convert(source: T, destinationClass: Class<D>): D
fun <D> convert(source: Any, destinationClass: Class<D>): D
fun <T, D> convert(source: T, destinationType: JsonTypeReference<D>): D
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D
fun addJsonConverter(c: JsonConverter<*, *>)
fun addJsonStringConverter(c: JsonStringConverter<*>)
fun addJsonConverter(c: BaseJsonConverter<*, *>)
}
@@ -0,0 +1,56 @@
/*
* 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 JsonException.kt
* LastUpdate 2026-02-05 11:12:36
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api.exception
/**
* 自定义异常类,用于处理 JSON 相关操作中出现的错误。
*
* 该类继承自 [RuntimeException],提供了三种构造函数以支持不同的异常场景:
* 1. 仅包含错误信息的构造函数。
* 2. 包含错误信息和原因(Throwable)的构造函数。
* 3. 仅包含原因(Throwable)的构造函数。
*/
class JsonException : RuntimeException {
/**
* 构造函数:创建一个带有指定错误信息的 [JsonException] 实例。
*
* @param message 错误信息描述。
*/
constructor(message: String) : super(message)
/**
* 构造函数:创建一个带有指定错误信息和原因的 [JsonException] 实例。
*
* @param message 错误信息描述。
* @param cause 导致此异常的根本原因。
*/
constructor(message: String, cause: Throwable) : super(message, cause)
/**
* 构造函数:创建一个由指定原因引发的 [JsonException] 实例。
*
* @param cause 导致此异常的根本原因。
*/
constructor(cause: Throwable) : super(cause)
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,11 +16,11 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonTypeReference.kt
* LastUpdate 2025-09-15 22:32:50
* LastUpdate 2026-02-05 11:12:36
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api.type
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
@@ -68,8 +68,7 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
* @return 类型引用实例
*/
companion object {
@JvmStatic
fun <T> of(): JsonTypeReference<T> {
inline fun <reified T> of(): JsonTypeReference<T> {
return object : JsonTypeReference<T>() {}
}
@@ -116,6 +115,11 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
throw IllegalStateException("无法获取原始类型: $type")
}
/**
* 判断两个 JsonTypeReference 实例是否相等
* @param other 另一个对象
* @return 是否相等
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this.javaClass != other.javaClass) return false
@@ -142,6 +146,10 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
return Objects.equals(type, that.type)
}
/**
* 计算当前实例的哈希码
* @return 哈希码值
*/
override fun hashCode(): Int {
if (type is ParameterizedType) {
val paramType = type as ParameterizedType
@@ -154,10 +162,19 @@ abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
return Objects.hash(type)
}
/**
* 返回当前实例的字符串表示形式
* @return 字符串描述
*/
override fun toString(): String {
return "JsonTypeReference{$type}"
return "com.mingliqiye.utils.json.JsonTypeReference<${TypeReference.getRawString(type)}>"
}
/**
* 比较当前实例与另一个实例的大小关系
* @param other 另一个 JsonTypeReference 实例
* @return 比较结果
*/
override fun compareTo(other: JsonTypeReference<T>): Int {
return this.type.toString().compareTo(other.type.toString())
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,12 +16,12 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonTypeUtils.kt
* LastUpdate 2025-09-17 11:12:06
* LastUpdate 2026-02-04 21:00:48
* UpdateUser MingLiPro
*/
@file:JvmName("JsonTypeUtils")
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api.type
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
@@ -0,0 +1,76 @@
/*
* 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 TypeReference.kt
* LastUpdate 2026-02-04 21:00:48
* 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
class TypeReference(
val rawClass: Type,
vararg paramType: Type
) : ParameterizedType {
private val typeArguments: Array<out Type> = paramType
override fun getActualTypeArguments(): Array<out Type> = typeArguments
override fun getRawType(): Type = rawClass
override fun getOwnerType(): Type? = null
override fun toString(): String = "${getRawString(rawType)}<${
",".join(typeArguments, TypeReference::getRawString)
}>"
companion object {
fun getRawString(s: Any): String {
if (s is Class<*>) {
return s.name
}
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 {
return of((object : JsonTypeReference<T>() {}).type)
}
fun of(type: Type): TypeReference {
if (type is Class<*>) {
return TypeReference(type)
}
if (type is ParameterizedType) {
return TypeReference(type.rawType, *type.actualTypeArguments)
}
throw IllegalStateException("无法获取类型: $type")
}
}
}
@@ -0,0 +1,102 @@
/*
* 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 DateTimeJsonConverter.kt
* LastUpdate 2026-02-05 11:18:57
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.AnnotationGetter.Companion.get
import com.mingliqiye.utils.json.converters.base.BaseJsonStringConverter
import com.mingliqiye.utils.objects.isNull
import com.mingliqiye.utils.string.isNullish
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.DateTimeJsonFormat
import com.mingliqiye.utils.time.Formatter
/**
* DateTimeJsonConverter 是一个用于处理 DateTime 类型与 JSON 字符串之间转换的类。
* 它继承自 BaseJsonStringConverter,提供了序列化(convert)和反序列化(deConvert)的功能。
*/
class DateTimeJsonConverter : BaseJsonStringConverter<DateTime> {
/**
* 将 DateTime 对象转换为 JSON 字符串。
*
* @param obj 需要转换的 DateTime 对象,可能为 null。
* @param annotationGetter 用于获取注解信息的对象,用于决定格式化方式。
* @return 转换后的字符串,如果输入为 null 则返回 null。
* @throws Exception 如果在转换过程中发生异常。
*/
@Throws(Exception::class)
override fun convert(obj: DateTime?, annotationGetter: AnnotationGetter): String? {
// 如果输入对象为 null,直接返回 null
if (obj.isNull()) return null
// 获取 DateTimeJsonFormat 注解信息
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>()
// 根据注解中的格式化规则进行转换
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
obj.format(dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
obj.format(dateTimeJsonFormat.formatter, dateTimeJsonFormat.repcZero)
} else {
obj.format()
}
}
/**
* 将 JSON 字符串转换为 DateTime 对象。
*
* @param obj 需要转换的字符串,可能为 null 或空。
* @param annotationGetter 用于获取注解信息的对象,用于决定解析方式。
* @return 解析后的 DateTime 对象,如果输入为 null 或空则返回 null。
* @throws Exception 如果在解析过程中发生异常。
*/
@Throws(Exception::class)
override fun deConvert(obj: String?, annotationGetter: AnnotationGetter): DateTime? {
// 如果输入字符串为 null 或空,直接返回 null
if (obj.isNullish()) return null
// 获取 DateTimeJsonFormat 注解信息
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.get<DateTimeJsonFormat>()
// 根据注解中的解析规则进行转换
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
} else if (dateTimeJsonFormat?.formatter?.isEmpty() == false) {
DateTime.parse(obj, dateTimeJsonFormat.formatter, dateTimeJsonFormat.repcZero)
} else {
DateTime.parse(obj)
}
}
/**
* 获取当前转换器支持的目标类型引用。
*
* @return 返回 DateTime 类型的 JsonTypeReference。
* @throws Exception 如果在获取类型引用时发生异常。
*/
@Throws(Exception::class)
override fun getFromType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
}
@@ -1,36 +0,0 @@
/*
* Copyright 2025 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 JsonConverter.kt
* LastUpdate 2025-09-15 11:12:07
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
interface JsonConverter<F, T> {
fun convert(obj: F?): T?
fun deConvert(obj: T?): F?
val tClass: Class<F>
fun getStringConverter(): JsonStringConverter<F>? {
if (this is JsonStringConverter<*>) {
return this as JsonStringConverter<F>
}
return null
}
}
@@ -1,251 +0,0 @@
/*
* Copyright 2025 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 JsonStringConverter.kt
* LastUpdate 2025-09-17 19:09:17
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.alibaba.fastjson2.JSONReader
import com.alibaba.fastjson2.JSONWriter
import com.alibaba.fastjson2.reader.ObjectReader
import com.alibaba.fastjson2.writer.ObjectWriter
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.module.SimpleModule
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.DateTime.Companion.parse
import com.mingliqiye.utils.uuid.UUID
import com.mingliqiye.utils.uuid.UUID.Companion.of
import java.io.IOException
import java.lang.reflect.Type
/**
* JSON转换器接口,提供对象与字符串之间的相互转换功能,并支持多种JSON库
*
* @param <T> 需要转换的对象类型
</T> */
abstract class JsonStringConverter<T> : JsonConverter<T, String> {
val fastjsonJsonStringConverterAdapter: FastjsonJsonStringConverterAdapter<JsonStringConverter<T>, T>
/**
* 获取 Fastjson 的适配器
* @return 适配器实例
*/
get() = FastjsonJsonStringConverterAdapter.of(this)
val gsonJsonStringConverterAdapter: GsonJsonStringConverterAdapter<JsonStringConverter<T>, T>
/**
* 获取 Gson 的适配器
* @return 适配器实例
*/
get() = GsonJsonStringConverterAdapter.of(this)
val jacksonJsonStringConverterAdapter: JacksonJsonStringConverterAdapter<JsonStringConverter<T>, T>
/**
* 获取 Jackson 的适配器
* @return 适配器实例
*/
get() = JacksonJsonStringConverterAdapter.of(this)
}
class JacksonJsonStringConverterAdapter<T : JsonStringConverter<TT>, TT
> private constructor(val jsonStringConverter: T) {
val jacksonJsonDeserializer: JsonDeserializer<TT?>
/**
* 获取Jackson反序列化器
*
* @return Jackson的JsonDeserializer实例
*/
get() = object : JsonDeserializer<TT?>() {
@Throws(IOException::class)
override fun deserialize(p: JsonParser, ctxt: DeserializationContext?): TT? {
if (p.isNaN) return null
return jsonStringConverter.deConvert(p.valueAsString)
}
}
val jacksonJsonSerializer: JsonSerializer<TT?>
/**
* 获取Jackson序列化器
*
* @return Jackson的JsonSerializer实例
*/
get() = object : JsonSerializer<TT?>() {
@Throws(IOException::class)
override fun serialize(
value: TT?,
gen: JsonGenerator,
serializers: SerializerProvider?
) {
if (value == null) {
gen.writeNull()
return
}
gen.writeString(jsonStringConverter.convert(value))
}
}
val jacksonModule: Module
/**
*
* 获取 Jackson 的格式化模块
*
* @return 格式化模块
*/
get() {
val tClass = jsonStringConverter.tClass
val m = SimpleModule(tClass.getSimpleName())
m.addSerializer<TT?>(tClass, this.jacksonJsonSerializer)
m.addDeserializer<TT?>(tClass, this.jacksonJsonDeserializer)
return m
}
companion object {
/**
*
* @param t JSON转换器实例
* @return JSON转换器的适配器
* @param <T> JSON转换器
* @param <TT> JSON转换器的泛型
**/
fun <T : JsonStringConverter<TT>, TT
> of(t: T): JacksonJsonStringConverterAdapter<T, TT> {
return JacksonJsonStringConverterAdapter(t)
}
}
}
class GsonJsonStringConverterAdapter<T : JsonStringConverter<TT>, TT
>(val jsonStringConverter: T) {
val gsonTypeAdapter: TypeAdapter<TT?>
/**
* 获取Gson类型适配器
*
* @return Gson的TypeAdapter实例
*/
get() = object : TypeAdapter<TT?>() {
@Throws(IOException::class)
override fun write(out: JsonWriter, value: TT?) {
if (value == null) {
out.nullValue()
return
}
out.value(jsonStringConverter.convert(value))
}
@Throws(IOException::class)
override fun read(`in`: JsonReader): TT? {
val value = `in`.nextString()
return jsonStringConverter.deConvert(value)
}
}
companion object {
fun <T : JsonStringConverter<TT>, TT
> of(t: T): GsonJsonStringConverterAdapter<T, TT> {
return GsonJsonStringConverterAdapter(t)
}
}
}
class FastjsonJsonStringConverterAdapter<T : JsonConverter<TT, String>, TT
>(val jsonStringConverter: T) {
@Suppress("UNCHECKED_CAST")
val fastJsonObjectWriter: ObjectWriter<T>
/**
* 获取FastJson对象写入器
*
* @return FastJson的ObjectWriter实例
*/
get() = ObjectWriter { writer: JSONWriter?, obj: Any?, _: Any?, _: Type?, _: Long
->
// 如果对象为null则写入null
if (obj == null) {
writer!!.writeNull()
return@ObjectWriter
}
writer!!.writeString(jsonStringConverter.convert(obj as TT))
}
val fastJsonObjectReader: ObjectReader<TT>
/**
* 获取FastJson对象读取器
*
* @return FastJson的ObjectReader实例
*/
get() = ObjectReader { reader: JSONReader?, _: Type?, _: Any?, _: Long
->
val value = reader!!.readString()
jsonStringConverter.deConvert(value)
}
companion object {
fun <T : JsonConverter<TT, String>, TT
> of(t: T): FastjsonJsonStringConverterAdapter<T, TT> {
return FastjsonJsonStringConverterAdapter(t)
}
}
}
class DateTimeJsonConverter : JsonStringConverter<DateTime>() {
override val tClass = DateTime::class.java
override fun convert(obj: DateTime?): String? {
if (obj == null) {
return null
}
return obj.format()
}
override fun deConvert(obj: String?): DateTime? {
if (obj == null) {
return null
}
return parse(
obj
)
}
}
class UUIDJsonStringConverter : JsonStringConverter<UUID>() {
override val tClass: Class<UUID> = UUID::class.java
override fun convert(obj: UUID?): String? {
if (obj == null) {
return null
}
return obj.getString()
}
override fun deConvert(obj: String?): UUID? {
if (obj == null) {
return null
}
return of(obj)
}
}
@@ -0,0 +1,101 @@
/*
* 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 UUIDJsonConverter.kt
* LastUpdate 2026-02-05 11:19:45
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.AnnotationGetter.Companion.get
import com.mingliqiye.utils.json.converters.base.BaseJsonStringConverter
import com.mingliqiye.utils.objects.isNull
import com.mingliqiye.utils.string.isNullish
import com.mingliqiye.utils.uuid.UUID
import com.mingliqiye.utils.uuid.UUIDFormatType
import com.mingliqiye.utils.uuid.UUIDJsonFormat
/**
* UUIDJsonConverter 是一个用于处理 UUID 类型与 JSON 字符串之间转换的类。
* 它继承自 BaseJsonStringConverter,并实现了 convert 和 deConvert 方法,
* 分别用于将 UUID 对象序列化为字符串以及反序列化字符串为 UUID 对象。
*/
class UUIDJsonConverter : BaseJsonStringConverter<UUID> {
/**
* 将 UUID 对象转换为字符串形式。
*
* @param obj 需要转换的 UUID 对象,可能为 null。
* @param annotationGetter 用于获取注解信息的对象。
* @return 转换后的字符串,如果输入为 null 则返回 null。
*/
override fun convert(
obj: UUID?,
annotationGetter: AnnotationGetter
): String? {
// 如果输入对象为 null,直接返回 null
if (obj.isNull()) return null
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认格式
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return obj.getString()
// 根据注解中的 base 和 value 属性选择合适的字符串表示方式
return if (BaseType.BASE16 != dateTimeJsonFormat.base) {
obj.getString(dateTimeJsonFormat.base)
} else if (UUIDFormatType.NO_UPPER_SPACE != dateTimeJsonFormat.value) {
obj.getString(dateTimeJsonFormat.value)
} else {
obj.getString()
}
}
/**
* 将字符串反序列化为 UUID 对象。
*
* @param obj 需要反序列化的字符串,可能为 null 或空。
* @param annotationGetter 用于获取注解信息的对象。
* @return 反序列化后的 UUID 对象,如果输入无效则返回 null。
*/
override fun deConvert(
obj: String?,
annotationGetter: AnnotationGetter
): UUID? {
// 如果输入字符串为 null 或空,直接返回 null
if (obj.isNullish()) return null
// 获取 UUIDJsonFormat 注解信息,若未找到则使用默认解析方式
val dateTimeJsonFormat: UUIDJsonFormat = annotationGetter.get<UUIDJsonFormat>() ?: return UUID.of(obj)
// 根据注解中的 base 属性选择合适的解析方式
return if (BaseType.BASE16 != dateTimeJsonFormat.base) {
UUID.of(obj, dateTimeJsonFormat.base)
} else {
UUID.of(obj)
}
}
/**
* 返回当前转换器支持的目标类型引用。
*
* @return 表示 UUID 类型的 JsonTypeReference 对象。
*/
override fun getFromType() = JsonTypeReference.of<UUID>()
}
@@ -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 AnnotationGetter.kt
* LastUpdate 2026-02-05 11:12:36
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
/**
* 定义一个用于获取注解的接口。
* 提供了一个通用方法来根据注解类型获取对应的注解实例。
*/
interface AnnotationGetter {
/**
* 根据指定的注解类型获取该类型的注解实例。
*
* @param clazz 注解的Class对象,表示要获取的注解类型。
* @return 返回对应类型的注解实例,如果未找到则返回null。
*/
fun <T : Annotation> get(clazz: Class<T>): T?
companion object {
/**
* 使用内联函数和重ified类型参数简化注解获取操作。
* 通过传入泛型参数自动推断注解类型,避免手动传递Class对象。
*
* @param T 注解类型,必须继承自Annotation。
* @return 返回对应类型的注解实例,如果未找到则返回null。
*/
inline fun <reified T : Annotation> AnnotationGetter.get(): T? = this.get(T::class.java)
/**
* 提供一个默认实现,始终返回null。
* 可用于需要空注解获取器的场景。
*/
val nullGetter = object : AnnotationGetter {
/**
* 始终返回null,不执行任何实际逻辑。
*
* @param clazz 注解的Class对象(未使用)。
* @return 始终返回null。
*/
override fun <T : Annotation> get(clazz: Class<T>): T? = null
}
}
}
@@ -0,0 +1,49 @@
/*
* 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 BaseJsonBigDecimalConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import java.math.BigDecimal
/**
* 接口 [BaseJsonBigDecimalConverter] 定义了一个用于将 JSON 数据转换为 [BigDecimal] 类型的转换器。
*
* 此接口继承自 [BaseJsonConverter],并指定目标类型为 [BigDecimal]。
* 实现此接口的类需要提供具体的转换逻辑。
*
* @param E 转换器处理的源数据类型。
*/
interface BaseJsonBigDecimalConverter<E> : BaseJsonConverter<E, BigDecimal> {
/**
* 获取目标类型的引用信息。
*
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [BigDecimal]。
* 通过调用 [JsonTypeReference.Companion.of] 方法创建类型引用。
*
* @return 目标类型 [BigDecimal] 的类型引用。
* @throws Exception 如果在获取类型引用时发生异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<BigDecimal>()
}
@@ -0,0 +1,45 @@
/*
* 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 BaseJsonBigIntegerConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import java.math.BigInteger
/**
* 接口 [BaseJsonBigIntegerConverter] 定义了一个用于将 JSON 数据转换为 `BigInteger` 类型的转换器。
* 该接口继承自 [BaseJsonConverter],并指定了泛型参数 [E] 和 `BigInteger`。
*
* @param E 表示需要转换的目标类型,由实现类具体指定。
*/
interface BaseJsonBigIntegerConverter<E> : BaseJsonConverter<E, BigInteger> {
/**
* 获取目标类型的引用,用于 JSON 反序列化时确定目标类型。
* 该方法重写了父接口中的 [getToType] 方法,并返回 `BigInteger` 类型的引用。
*
* @return 返回 [JsonTypeReference] 对象,表示 `BigInteger` 类型的引用。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<BigInteger>()
}
@@ -0,0 +1,46 @@
/*
* 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 BaseJsonBooleanConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonBooleanConverter] 定义了一个用于处理布尔类型 JSON 转换的基础转换器。
*
* 该接口继承自 [BaseJsonConverter],并专门用于将某种类型 [E] 转换为布尔类型 [Boolean]。
* 实现该接口的类需要提供具体的转换逻辑。
*/
interface BaseJsonBooleanConverter<E> : BaseJsonConverter<E, Boolean> {
/**
* 获取目标类型的引用信息。
*
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [Boolean]。
* 此方法重写了父接口中的定义,并通过 [JsonTypeReference.Companion.of] 方法获取布尔类型的引用。
*
* @return [JsonTypeReference<Boolean>] 表示布尔类型的引用。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Boolean>()
}
@@ -0,0 +1,43 @@
/*
* 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 BaseJsonByteConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* BaseJsonByteConverter 是一个接口,继承自 BaseJsonConverter,用于定义字节类型(Byte)的 JSON 转换器。
*
* 该接口的主要作用是提供一个标准的字节类型转换实现,并通过 getToType 方法返回目标类型的引用。
*
* @param E 泛型参数,表示需要转换的目标对象类型。
*/
interface BaseJsonByteConverter<E> : BaseJsonConverter<E, Byte> {
/**
* 获取目标类型的引用,用于标识转换的目标类型为 Byte。
*
* @return 返回 JsonTypeReference 类型的实例,表示目标类型为 Byte。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Byte>()
}
@@ -0,0 +1,210 @@
/*
* 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 BaseJsonConverter.kt
* LastUpdate 2026-02-05 11:16:12
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.deser.ContextualDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.ContextualSerializer
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import java.math.BigDecimal
import java.math.BigInteger
/**
* BaseJsonConverter 是一个通用的 JSON 转换器接口,用于定义对象之间的双向转换逻辑。
*
* @param F 源类型,表示需要被转换的对象类型。
* @param T 目标类型,表示转换后的对象类型。
*/
interface BaseJsonConverter<F, T> {
/**
* 将源对象转换为目标对象。
*
* @param obj 源对象,可能为 null。
* @param annotationGetter 注解获取器,用于获取字段上的注解信息。
* @return 转换后的目标对象,可能为 null。
* @throws Exception 转换过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun convert(obj: F?, annotationGetter: AnnotationGetter): T?
/**
* 将目标对象反向转换为源对象。
*
* @param obj 目标对象,可能为 null。
* @param annotationGetter 注解获取器,用于获取字段上的注解信息。
* @return 反向转换后的源对象,可能为 null。
* @throws Exception 转换过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun deConvert(obj: T?, annotationGetter: AnnotationGetter): F?
/**
* 获取源类型的类型引用。
*
* @return 源类型的 JsonTypeReference 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getFromType(): JsonTypeReference<F>
/**
* 获取目标类型的类型引用。
*
* @return 目标类型的 JsonTypeReference 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getToType(): JsonTypeReference<T>
/**
* 获取源类型的原始类。
*
* @return 源类型的 Class 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getFromClass() = getFromType().getRawType()
/**
* 获取目标类型的原始类。
*
* @return 目标类型的 Class 对象。
* @throws Exception 获取过程中可能抛出的异常。
*/
@Throws(Exception::class)
fun getToClass() = getToType().getRawType()
/**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
*
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
*/
fun getJacksonModule(): SimpleModule {
// 创建一个 Jackson 模块,名称由源类型和目标类型组成
val module = SimpleModule("${getFromClass().name}To${getToClass().name}")
// 定义自定义序列化器
val serializer = object : JsonSerializer<F>(), ContextualSerializer {
var property: BeanProperty? = null
/**
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
*
* @param value 源对象,可能为 null。
* @param gen JSON 生成器,用于写入 JSON 数据。
* @param provider 序列化提供者,可选参数。
*/
override fun serialize(
value: F?,
gen: JsonGenerator,
provider: SerializerProvider?
) {
// 执行转换逻辑
val data: T? = convert(value, object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
// 根据目标对象的类型写入对应的 JSON 值
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")
}
}
/**
* 上下文感知方法:设置当前属性信息。
*
* @param prov 序列化提供者,可选参数。
* @param property 当前属性信息。
* @return 返回当前序列化器实例。
*/
override fun createContextual(
prov: SerializerProvider?,
property: BeanProperty?
): JsonSerializer<F> {
this.property = property
return this
}
}
// 定义自定义反序列化器
val deserializer = object : JsonDeserializer<F>(), ContextualDeserializer {
/**
* 反序列化方法:从 JSON 解析数据并转换回源对象。
*
* @param p JSON 解析器。
* @param ctxt 反序列化上下文,可选参数。
* @return 转换后的源对象,可能为 null。
*/
override fun deserialize(
p: JsonParser,
ctxt: DeserializationContext?
): F? {
// 处理 null 值情况
if (p.currentToken == JsonToken.VALUE_NULL) return null
// 执行反向转换逻辑
return deConvert(p.readValueAs(getToClass()), object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
}
var property: BeanProperty? = null
/**
* 上下文感知方法:设置当前属性信息。
*
* @param ctxt 反序列化上下文,可选参数。
* @param property 当前属性信息。
* @return 返回当前反序列化器实例。
*/
override fun createContextual(
ctxt: DeserializationContext?,
property: BeanProperty?
): JsonDeserializer<F> {
this.property = property
return this
}
}
// 将自定义序列化器和反序列化器注册到模块中
return module
.addSerializer(getFromClass(), serializer)
.addDeserializer(getFromClass(), deserializer)
}
}
@@ -0,0 +1,42 @@
/*
* 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 BaseJsonDoubleConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* BaseJsonDoubleConverter 是一个接口,继承自 BaseJsonConverter,
* 用于定义将 JSON 数据转换为 Double 类型的转换器。
*
* @param E 泛型参数,表示需要转换的目标类型。
*/
interface BaseJsonDoubleConverter<E> : BaseJsonConverter<E, Double> {
/**
* 获取目标类型的引用,用于标识转换的目标类型为 Double。
*
* @return 返回 JsonTypeReference<Double> 类型的实例,表示目标类型为 Double。
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Double>()
}
@@ -0,0 +1,46 @@
/*
* 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 BaseJsonFloatConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonFloatConverter] 定义了一个用于处理浮点数类型 JSON 转换的基础转换器。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Float],
* 表示将某种类型 [E] 转换为 [Float] 类型的 JSON 数据。
*/
interface BaseJsonFloatConverter<E> : BaseJsonConverter<E, Float> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Float] 类型的 [JsonTypeReference] 实例。
* 用于标识当前转换器的目标类型为 [Float]。
*
* @return [JsonTypeReference] 表示 [Float] 类型的引用信息。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Float>()
}
@@ -0,0 +1,46 @@
/*
* 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 BaseJsonIntConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonIntConverter] 是一个泛型接口,继承自 [BaseJsonConverter],
* 用于定义将 JSON 数据转换为 [Int] 类型的转换器。
*
* @param E 表示需要转换的目标类型,通常是一个具体的业务实体或数据模型。
*/
interface BaseJsonIntConverter<E> : BaseJsonConverter<E, Int> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Int] 类型的 [JsonTypeReference] 实例。
* 用于标识当前转换器的目标类型为 [Int]。
*
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Int]。
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Int>()
}
@@ -0,0 +1,43 @@
/*
* 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 BaseJsonLongConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonLongConverter] 定义了一个用于将 JSON 数据转换为 Long 类型的转换器。
*
* 此接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Long],
* 表示该转换器处理的是从类型 [E] 到 [Long] 的转换。
*/
interface BaseJsonLongConverter<E> : BaseJsonConverter<E, Long> {
/**
* 获取目标类型的引用,用于标识此转换器的目标类型为 [Long]。
*
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Long]。
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Long>()
}
@@ -0,0 +1,46 @@
/*
* 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 BaseJsonShortConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonShortConverter] 定义了一个用于将 JSON 数据转换为 Short 类型的转换器。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [Short],
* 表示该转换器处理的源类型为 [E],目标类型为 [Short]。
*/
interface BaseJsonShortConverter<E> : BaseJsonConverter<E, Short> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回 [Short] 类型的 [JsonTypeReference] 实例。
* 通过 [JsonTypeReference.Companion.of] 方法创建类型引用。
*
* @return [JsonTypeReference] 表示 [Short] 类型的引用。
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<Short>()
}
@@ -0,0 +1,46 @@
/*
* 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 BaseJsonStringConverter.kt
* LastUpdate 2026-02-05 11:20:59
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
/**
* 接口 [BaseJsonStringConverter] 定义了一个用于 JSON 字符串转换的基础接口。
*
* 该接口继承自 [BaseJsonConverter],并指定泛型参数 [E] 和 [String],
* 表示将类型 [E] 转换为字符串类型的 JSON 数据。
*/
interface BaseJsonStringConverter<E> : BaseJsonConverter<E, String> {
/**
* 获取目标类型的引用信息。
*
* 该方法重写了父接口中的 [getToType] 方法,返回一个表示 [String] 类型的 [JsonTypeReference] 实例。
* 此方法可能抛出异常,因此使用 [@Throws(Exception::class)] 注解标记。
*
* @return 返回一个 [JsonTypeReference] 实例,表示目标类型为 [String]。
* @throws Exception 如果在获取类型引用时发生错误,则抛出此异常。
*/
@Throws(Exception::class)
override fun getToType() = JsonTypeReference.of<String>()
}
@@ -0,0 +1,59 @@
/*
* 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 JsonConverter.kt
* LastUpdate 2026-02-05 11:18:33
* UpdateUser MingLiPro
*/
@file:JvmName("JsonConverter")
package com.mingliqiye.utils.json.converters.base
import com.fasterxml.jackson.databind.ObjectMapper
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
* 获取给定类型的实际类对象。
*
* @param type 类型对象,可以是Class、ParameterizedType或其他Type的实现。
* @return 返回与给定类型对应的Class对象;如果无法解析,则返回null。
*/
fun getClass(type: Type?): Class<*>? {
// 尝试将type直接转换为Class类型,如果失败则检查是否为ParameterizedType
val clazz: Class<*>? = type as? Class<*> ?: if (type is ParameterizedType) {
// 如果是ParameterizedType,则递归获取其原始类型
getClass(type.rawType)
} else {
// 其他情况返回null
null
}
return clazz
}
/**
* 扩展ObjectMapper,用于注册指定类型的模块。
*
* 此函数通过反射创建指定类型的实例,并调用其getJacksonModule方法来获取Jackson模块,
* 然后将该模块注册到当前ObjectMapper实例中。
*
* @param T 必须继承自BaseJsonConverter的泛型类型。
* @return 返回注册了模块后的ObjectMapper实例。
*/
inline fun <reified T : BaseJsonConverter<*, *>> ObjectMapper.registerModule(): ObjectMapper =
this.registerModule(T::class.java.newInstance().getJacksonModule())