style: 全项目统一 Tab 缩进并补全尾随逗号
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -38,211 +38,211 @@ import java.lang.reflect.Type
|
||||
|
||||
class Jackson3JsonApi : JsonApi {
|
||||
|
||||
var get: () -> ObjectMapper = { _prObjectMapper!! }
|
||||
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
|
||||
var get: () -> ObjectMapper = { _prObjectMapper!! }
|
||||
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
|
||||
|
||||
private var _prObjectMapper: ObjectMapper? = null
|
||||
private var _prObjectMapper: ObjectMapper? = null
|
||||
|
||||
|
||||
var objectMapper: ObjectMapper
|
||||
get() = get()
|
||||
private set(value) = set(value)
|
||||
var objectMapper: ObjectMapper
|
||||
get() = get()
|
||||
private set(value) = set(value)
|
||||
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
_prObjectMapper = objectMapper
|
||||
}
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
_prObjectMapper = objectMapper
|
||||
}
|
||||
|
||||
constructor(
|
||||
get: () -> ObjectMapper,
|
||||
set: (ObjectMapper) -> Unit,
|
||||
) {
|
||||
this.get = get
|
||||
this.set = set
|
||||
}
|
||||
constructor(
|
||||
get: () -> ObjectMapper,
|
||||
set: (ObjectMapper) -> Unit,
|
||||
) {
|
||||
this.get = get
|
||||
this.set = set
|
||||
}
|
||||
|
||||
constructor() {
|
||||
_prObjectMapper = ObjectMapper()
|
||||
}
|
||||
constructor() {
|
||||
_prObjectMapper = ObjectMapper()
|
||||
}
|
||||
|
||||
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, 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 <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 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 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 (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
override fun isValidJson(json: String): Boolean {
|
||||
return try {
|
||||
objectMapper.readTree(json)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
override fun merge(vararg jsons: String): String {
|
||||
try {
|
||||
if (jsons.isEmpty()) return "{}"
|
||||
override fun merge(vararg jsons: String): String {
|
||||
try {
|
||||
if (jsons.isEmpty()) return "{}"
|
||||
|
||||
val resultNode = objectMapper.createObjectNode()
|
||||
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")
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
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() }
|
||||
// 处理 JSON Pointer 路径
|
||||
val pathParts = path.split("/").filter { it.isNotEmpty() }
|
||||
|
||||
if (pathParts.isEmpty()) {
|
||||
// 替换整个根节点
|
||||
return objectMapper.writeValueAsString(newValue)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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")
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
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, 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)
|
||||
}
|
||||
}
|
||||
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
|
||||
// 辅助方法:查找父节点
|
||||
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("/")}")
|
||||
}
|
||||
// 遍历到最后一个元素之前(即找到父节点)
|
||||
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
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
|
||||
val mapperBuilder = Jackson3ApiJavaHelper.rebuild(objectMapper)
|
||||
mapperBuilder.addModule(c.getJackson3Module())
|
||||
this.objectMapper = mapperBuilder.build()
|
||||
}
|
||||
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
|
||||
val mapperBuilder = Jackson3ApiJavaHelper.rebuild(objectMapper)
|
||||
mapperBuilder.addModule(c.getJackson3Module())
|
||||
this.objectMapper = mapperBuilder.build()
|
||||
}
|
||||
|
||||
override fun parseJsonItem(json: String): JsonItem {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parseJsonItem", e)
|
||||
}
|
||||
}
|
||||
override fun parseJsonItem(json: String): JsonItem {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parseJsonItem", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class JackSon3JsonItem : JsonItem {
|
||||
companion object {
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSon3JsonObject(node)
|
||||
JsonNodeType.ARRAY -> JackSon3JsonArray(node)
|
||||
JsonNodeType.BOOLEAN -> JackSon3JsonBoolean(node)
|
||||
JsonNodeType.NULL -> JsonNull()
|
||||
JsonNodeType.NUMBER -> JackSon3JsonNumber(node)
|
||||
JsonNodeType.STRING -> JackSon3JsonString(node)
|
||||
else -> throw IllegalStateException("unknown type ${node.nodeType}")
|
||||
}
|
||||
}
|
||||
}
|
||||
companion object {
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSon3JsonObject(node)
|
||||
JsonNodeType.ARRAY -> JackSon3JsonArray(node)
|
||||
JsonNodeType.BOOLEAN -> JackSon3JsonBoolean(node)
|
||||
JsonNodeType.NULL -> JsonNull()
|
||||
JsonNodeType.NUMBER -> JackSon3JsonNumber(node)
|
||||
JsonNodeType.STRING -> JackSon3JsonString(node)
|
||||
else -> throw IllegalStateException("unknown type ${node.nodeType}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString())
|
||||
@@ -251,47 +251,47 @@ class JackSon3JsonString(node: JsonNode) : JsonString(node.asString())
|
||||
|
||||
|
||||
class JackSon3JsonArray(val node: JsonNode) : JsonArray() {
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
return JackSon3JsonItem.getJsonItem(node.get(index))
|
||||
}
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
return JackSon3JsonItem.getJsonItem(node.get(index))
|
||||
}
|
||||
|
||||
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
val iteet = node.iterator().withIndex()
|
||||
return object : Iterator<IndexedValue<JsonItem>> {
|
||||
override fun next(): IndexedValue<JsonItem> {
|
||||
val it = iteet.next()
|
||||
return IndexedValue(it.index, JackSon3JsonItem.getJsonItem(it.value))
|
||||
}
|
||||
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
val iteet = node.iterator().withIndex()
|
||||
return object : Iterator<IndexedValue<JsonItem>> {
|
||||
override fun next(): IndexedValue<JsonItem> {
|
||||
val it = iteet.next()
|
||||
return IndexedValue(it.index, JackSon3JsonItem.getJsonItem(it.value))
|
||||
}
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return iteet.hasNext()
|
||||
}
|
||||
override fun hasNext(): Boolean {
|
||||
return iteet.hasNext()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class JackSon3JsonObject(val node: JsonNode) : JsonObject() {
|
||||
override fun getField(name: String): JsonItem {
|
||||
return JackSon3JsonItem.getJsonItem(node.get(name))
|
||||
}
|
||||
override fun getField(name: String): JsonItem {
|
||||
return JackSon3JsonItem.getJsonItem(node.get(name))
|
||||
}
|
||||
|
||||
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
return object : Iterator<Map.Entry<String, JsonItem>> {
|
||||
val it = node.properties().iterator()
|
||||
override fun next(): Map.Entry<String, JsonItem> {
|
||||
val utem = it.next()
|
||||
return object : Map.Entry<String, JsonItem> {
|
||||
override val key: String
|
||||
get() = utem.key
|
||||
override val value: JsonItem
|
||||
get() = JackSon3JsonItem.getJsonItem(utem.value)
|
||||
}
|
||||
}
|
||||
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
return object : Iterator<Map.Entry<String, JsonItem>> {
|
||||
val it = node.properties().iterator()
|
||||
override fun next(): Map.Entry<String, JsonItem> {
|
||||
val utem = it.next()
|
||||
return object : Map.Entry<String, JsonItem> {
|
||||
override val key: String
|
||||
get() = utem.key
|
||||
override val value: JsonItem
|
||||
get() = JackSon3JsonItem.getJsonItem(utem.value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return it.hasNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun hasNext(): Boolean {
|
||||
return it.hasNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,284 +42,284 @@ import com.mingliqiye.utils.json.objects.base.*
|
||||
*/
|
||||
class JacksonJsonApi : JsonApi {
|
||||
|
||||
private val objectMapper: ObjectMapper
|
||||
private val objectMapper: ObjectMapper
|
||||
|
||||
/**
|
||||
* 使用默认的ObjectMapper构造实例
|
||||
*/
|
||||
constructor() {
|
||||
this.objectMapper = ObjectMapper()
|
||||
}
|
||||
/**
|
||||
* 使用默认的ObjectMapper构造实例
|
||||
*/
|
||||
constructor() {
|
||||
this.objectMapper = ObjectMapper()
|
||||
}
|
||||
|
||||
fun getObjectMapper() = objectMapper
|
||||
fun getObjectMapper() = objectMapper
|
||||
|
||||
/**
|
||||
* 使用指定的ObjectMapper构造实例
|
||||
*
|
||||
* @param objectMapper 自定义的ObjectMapper实例
|
||||
*/
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
this.objectMapper = objectMapper
|
||||
}
|
||||
/**
|
||||
* 使用指定的ObjectMapper构造实例
|
||||
*
|
||||
* @param objectMapper 自定义的ObjectMapper实例
|
||||
*/
|
||||
constructor(objectMapper: ObjectMapper) {
|
||||
this.objectMapper = objectMapper
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为指定类型的对象
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param clazz 目标对象类型
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, clazz: Class<T>): T {
|
||||
return try {
|
||||
objectMapper.readValue(json, clazz)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 将JSON字符串解析为指定类型的对象
|
||||
*
|
||||
* @param json 待解析的JSON字符串
|
||||
* @param clazz 目标对象类型
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, clazz: Class<T>): T {
|
||||
return try {
|
||||
objectMapper.readValue(json, clazz)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串解析为复杂泛型结构的对象(如List、Map等)
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param type 泛型类型引用
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
|
||||
return try {
|
||||
val reader: ObjectReader = objectMapper.readerFor(
|
||||
objectMapper.constructType(type.type)
|
||||
)
|
||||
reader.readValue(json)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 将JSON字符串解析为复杂泛型结构的对象(如List、Map等)
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param type 泛型类型引用
|
||||
* @param <T> 泛型参数,表示目标对象类型
|
||||
* @return 解析后的对象
|
||||
* @throws JsonException 当解析失败时抛出异常
|
||||
*/
|
||||
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
|
||||
return try {
|
||||
val reader: ObjectReader = objectMapper.readerFor(
|
||||
objectMapper.constructType(type.type)
|
||||
)
|
||||
reader.readValue(json)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parse JSON string", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为JSON字符串
|
||||
*
|
||||
* @return 格式化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun format(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 将对象格式化为JSON字符串
|
||||
*
|
||||
* @return 格式化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun format(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun formatUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(throwable = e)
|
||||
}
|
||||
}
|
||||
fun formatUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(throwable = e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象格式化为美化(带缩进)的JSON字符串
|
||||
*
|
||||
* @return 美化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun formatPretty(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 将对象格式化为美化(带缩进)的JSON字符串
|
||||
*
|
||||
* @return 美化后的JSON字符串
|
||||
* @throws JsonException 当格式化失败时抛出异常
|
||||
*/
|
||||
override fun formatPretty(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun formatPrettyUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
|
||||
.writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
fun formatPrettyUnicode(obj: Any): String {
|
||||
return try {
|
||||
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
|
||||
.writeValueAsString(obj)
|
||||
} catch (e: Exception) {
|
||||
throw JsonException(
|
||||
"Failed to format object to pretty JSON string", e
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断给定字符串是否是有效的JSON格式
|
||||
*
|
||||
* @param json 待验证的字符串
|
||||
* @return 如果是有效JSON返回true,否则返回false
|
||||
*/
|
||||
override fun isValidJson(json: String): Boolean {
|
||||
return try {
|
||||
objectMapper.readTree(json)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 判断给定字符串是否是有效的JSON格式
|
||||
*
|
||||
* @param json 待验证的字符串
|
||||
* @return 如果是有效JSON返回true,否则返回false
|
||||
*/
|
||||
override fun isValidJson(json: String): Boolean {
|
||||
return try {
|
||||
objectMapper.readTree(json)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并多个JSON字符串为一个JSON对象
|
||||
*
|
||||
* @param jsons 多个JSON字符串
|
||||
* @return 合并后的JSON字符串
|
||||
* @throws JsonException 当合并失败时抛出异常
|
||||
*/
|
||||
override fun merge(vararg jsons: String): String {
|
||||
val result: ObjectNode = objectMapper.createObjectNode()
|
||||
for (json in jsons) {
|
||||
try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node.isObject) {
|
||||
result.setAll<JsonNode>(node as ObjectNode)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
return try {
|
||||
objectMapper.writeValueAsString(result)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException("Failed to merge JSON strings", e)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 合并多个JSON字符串为一个JSON对象
|
||||
*
|
||||
* @param jsons 多个JSON字符串
|
||||
* @return 合并后的JSON字符串
|
||||
* @throws JsonException 当合并失败时抛出异常
|
||||
*/
|
||||
override fun merge(vararg jsons: String): String {
|
||||
val result: ObjectNode = objectMapper.createObjectNode()
|
||||
for (json in jsons) {
|
||||
try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node.isObject) {
|
||||
result.setAll<JsonNode>(node as ObjectNode)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
return try {
|
||||
objectMapper.writeValueAsString(result)
|
||||
} catch (e: JsonProcessingException) {
|
||||
throw JsonException("Failed to merge JSON strings", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @return 节点值的文本表示,如果路径不存在则返回null
|
||||
* @throws JsonException 当获取节点值失败时抛出异常
|
||||
*/
|
||||
override fun getNodeValue(json: String, path: String): String? {
|
||||
return try {
|
||||
var node: JsonNode = objectMapper.readTree(json)
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
for (p in paths) {
|
||||
node = node.get(p)
|
||||
}
|
||||
node.asText()
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to get node value", e)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @return 节点值的文本表示,如果路径不存在则返回null
|
||||
* @throws JsonException 当获取节点值失败时抛出异常
|
||||
*/
|
||||
override fun getNodeValue(json: String, path: String): String? {
|
||||
return try {
|
||||
var node: JsonNode = objectMapper.readTree(json)
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
for (p in paths) {
|
||||
node = node.get(p)
|
||||
}
|
||||
node.asText()
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to get node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @param newValue 新的节点值
|
||||
* @return 更新后的JSON字符串
|
||||
* @throws JsonException 当更新节点值失败时抛出异常
|
||||
*/
|
||||
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
|
||||
return try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node is ObjectNode) {
|
||||
val objectNode: ObjectNode = node
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
var current: JsonNode = objectNode
|
||||
/**
|
||||
* 更新JSON字符串中指定路径的节点值
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param path 节点路径,使用"."分隔
|
||||
* @param newValue 新的节点值
|
||||
* @return 更新后的JSON字符串
|
||||
* @throws JsonException 当更新节点值失败时抛出异常
|
||||
*/
|
||||
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
|
||||
return try {
|
||||
val node: JsonNode = objectMapper.readTree(json)
|
||||
if (node is ObjectNode) {
|
||||
val objectNode: ObjectNode = node
|
||||
val paths: Array<String> = path.split("\\.".toRegex()).toTypedArray()
|
||||
var current: JsonNode = objectNode
|
||||
|
||||
// 导航到目标节点的父节点
|
||||
for (i in 0 until paths.size - 1) {
|
||||
current = current.get(paths[i])
|
||||
if (current !is ObjectNode) {
|
||||
return json // 路径不存在或无效
|
||||
}
|
||||
}
|
||||
// 导航到目标节点的父节点
|
||||
for (i in 0 until paths.size - 1) {
|
||||
current = current.get(paths[i])
|
||||
if (current !is ObjectNode) {
|
||||
return json // 路径不存在或无效
|
||||
}
|
||||
}
|
||||
|
||||
// 更新值
|
||||
if (current is ObjectNode) {
|
||||
val parent: ObjectNode = current
|
||||
parent.set<JsonNode>(
|
||||
paths[paths.size - 1], objectMapper.valueToTree(newValue)
|
||||
)
|
||||
}
|
||||
// 更新值
|
||||
if (current is ObjectNode) {
|
||||
val parent: ObjectNode = current
|
||||
parent.set<JsonNode>(
|
||||
paths[paths.size - 1], objectMapper.valueToTree(newValue)
|
||||
)
|
||||
}
|
||||
|
||||
objectMapper.writeValueAsString(objectNode)
|
||||
}
|
||||
json
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
objectMapper.writeValueAsString(objectNode)
|
||||
}
|
||||
json
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在不同对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationClass 目标对象类型
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
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)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 在不同对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationClass 目标对象类型
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在不同泛型对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationType 目标对象的泛型类型引用
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
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)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 在不同泛型对象类型之间进行转换
|
||||
*
|
||||
* @param source 源对象
|
||||
* @param destinationType 目标对象的泛型类型引用
|
||||
* @param <T> 源对象类型
|
||||
* @param <D> 目标对象类型
|
||||
* @return 转换后的对象
|
||||
*/
|
||||
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 addJsonConverter(c: BaseJsonConverter<*, *>) {
|
||||
try {
|
||||
objectMapper.registerModule(c.getJacksonModule())
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
|
||||
try {
|
||||
objectMapper.registerModule(c.getJacksonModule())
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to update node value", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun parseJsonItem(json: String): JsonItem {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parseJsonItem", e)
|
||||
}
|
||||
}
|
||||
override fun parseJsonItem(json: String): JsonItem {
|
||||
try {
|
||||
return getJsonItem(objectMapper.readTree(json))
|
||||
} catch (e: Exception) {
|
||||
throw JsonException("Failed to parseJsonItem", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class JackSonJsonItem : JsonItem {
|
||||
companion object {
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSonJsonObject(node)
|
||||
JsonNodeType.ARRAY -> JackSonJsonArray(node)
|
||||
JsonNodeType.BOOLEAN -> JackSonJsonBoolean(node)
|
||||
JsonNodeType.NULL -> JsonNull()
|
||||
JsonNodeType.NUMBER -> JackSonJsonNumber(node)
|
||||
JsonNodeType.STRING -> JackSonJsonString(node)
|
||||
else -> throw IllegalStateException("unknown type ${node.nodeType}")
|
||||
}
|
||||
}
|
||||
}
|
||||
companion object {
|
||||
fun getJsonItem(node: JsonNode): JsonItem {
|
||||
return when (node.nodeType) {
|
||||
JsonNodeType.OBJECT -> JackSonJsonObject(node)
|
||||
JsonNodeType.ARRAY -> JackSonJsonArray(node)
|
||||
JsonNodeType.BOOLEAN -> JackSonJsonBoolean(node)
|
||||
JsonNodeType.NULL -> JsonNull()
|
||||
JsonNodeType.NUMBER -> JackSonJsonNumber(node)
|
||||
JsonNodeType.STRING -> JackSonJsonString(node)
|
||||
else -> throw IllegalStateException("unknown type ${node.nodeType}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText())
|
||||
@@ -328,47 +328,47 @@ class JackSonJsonString(node: JsonNode) : JsonString(node.asText())
|
||||
|
||||
|
||||
class JackSonJsonArray(val node: JsonNode) : JsonArray() {
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
return getJsonItem(node.get(index))
|
||||
}
|
||||
override fun getIndex(index: Int): JsonItem {
|
||||
return getJsonItem(node.get(index))
|
||||
}
|
||||
|
||||
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
val iteet = node.iterator().withIndex()
|
||||
return object : Iterator<IndexedValue<JsonItem>> {
|
||||
override fun next(): IndexedValue<JsonItem> {
|
||||
val it = iteet.next()
|
||||
return IndexedValue(it.index, getJsonItem(it.value))
|
||||
}
|
||||
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
val iteet = node.iterator().withIndex()
|
||||
return object : Iterator<IndexedValue<JsonItem>> {
|
||||
override fun next(): IndexedValue<JsonItem> {
|
||||
val it = iteet.next()
|
||||
return IndexedValue(it.index, getJsonItem(it.value))
|
||||
}
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return iteet.hasNext()
|
||||
}
|
||||
override fun hasNext(): Boolean {
|
||||
return iteet.hasNext()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class JackSonJsonObject(val node: JsonNode) : JsonObject() {
|
||||
override fun getField(name: String): JsonItem {
|
||||
return getJsonItem(node.get(name))
|
||||
}
|
||||
override fun getField(name: String): JsonItem {
|
||||
return getJsonItem(node.get(name))
|
||||
}
|
||||
|
||||
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
return object : Iterator<Map.Entry<String, JsonItem>> {
|
||||
val it = node.properties().iterator()
|
||||
override fun next(): Map.Entry<String, JsonItem> {
|
||||
val utem = it.next()
|
||||
return object : Map.Entry<String, JsonItem> {
|
||||
override val key: String
|
||||
get() = utem.key
|
||||
override val value: JsonItem
|
||||
get() = getJsonItem(utem.value)
|
||||
}
|
||||
}
|
||||
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
return object : Iterator<Map.Entry<String, JsonItem>> {
|
||||
val it = node.properties().iterator()
|
||||
override fun next(): Map.Entry<String, JsonItem> {
|
||||
val utem = it.next()
|
||||
return object : Map.Entry<String, JsonItem> {
|
||||
override val key: String
|
||||
get() = utem.key
|
||||
override val value: JsonItem
|
||||
get() = getJsonItem(utem.value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return it.hasNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun hasNext(): Boolean {
|
||||
return it.hasNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -34,148 +34,148 @@ import java.util.*
|
||||
*/
|
||||
abstract class JsonTypeReference<T> : Comparable<JsonTypeReference<T>> {
|
||||
|
||||
open var type: Type = Any::class.java
|
||||
open var type: Type = Any::class.java
|
||||
|
||||
/**
|
||||
* 构造函数,通过反射获取泛型类型信息
|
||||
* 仅供内部匿名子类使用
|
||||
*/
|
||||
protected constructor() {
|
||||
val superClass: Type = this.javaClass.genericSuperclass
|
||||
/**
|
||||
* 构造函数,通过反射获取泛型类型信息
|
||||
* 仅供内部匿名子类使用
|
||||
*/
|
||||
protected constructor() {
|
||||
val superClass: Type = this.javaClass.genericSuperclass
|
||||
|
||||
// 检查是否为匿名子类,防止直接实例化导致无法获取泛型信息
|
||||
if (superClass is Class<*>) {
|
||||
throw IllegalArgumentException(
|
||||
"必须使用匿名子类方式创建 JsonTypeReference," +
|
||||
"例如: new JsonTypeReference<List<String>>() {}"
|
||||
)
|
||||
}
|
||||
// 检查是否为匿名子类,防止直接实例化导致无法获取泛型信息
|
||||
if (superClass is Class<*>) {
|
||||
throw IllegalArgumentException(
|
||||
"必须使用匿名子类方式创建 JsonTypeReference," +
|
||||
"例如: new JsonTypeReference<List<String>>() {}"
|
||||
)
|
||||
}
|
||||
|
||||
this.type = (superClass as ParameterizedType).actualTypeArguments[0]
|
||||
}
|
||||
this.type = (superClass as ParameterizedType).actualTypeArguments[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数,直接指定类型
|
||||
* @param type 具体的类型信息
|
||||
*/
|
||||
protected constructor(type: Type) {
|
||||
this.type = Objects.requireNonNull(type, "Type cannot be null")
|
||||
}
|
||||
/**
|
||||
* 构造函数,直接指定类型
|
||||
* @param type 具体的类型信息
|
||||
*/
|
||||
protected constructor(type: Type) {
|
||||
this.type = Objects.requireNonNull(type, "Type cannot be null")
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建类型引用实例
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
companion object {
|
||||
inline fun <reified T> of(): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>() {}
|
||||
}
|
||||
/**
|
||||
* 创建类型引用实例
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
companion object {
|
||||
inline fun <reified T> of(): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Class 创建类型引用
|
||||
* @param clazz 目标类
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(clazz: Class<T>): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(clazz) {}
|
||||
}
|
||||
/**
|
||||
* 根据 Class 创建类型引用
|
||||
* @param clazz 目标类
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(clazz: Class<T>): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(clazz) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 Type 创建类型引用
|
||||
* @param type 目标类型
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(type: Type): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(type) {}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 根据 Type 创建类型引用
|
||||
* @param type 目标类型
|
||||
* @param <T> 目标类型
|
||||
* @return 类型引用实例
|
||||
*/
|
||||
@JvmStatic
|
||||
fun <T> of(type: Type): JsonTypeReference<T> {
|
||||
return object : JsonTypeReference<T>(type) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取原始类型(去掉泛型参数的类型)
|
||||
* @return 原始类型 Class
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun getRawType(): Class<T> {
|
||||
var rawType: Type = type
|
||||
/**
|
||||
* 获取原始类型(去掉泛型参数的类型)
|
||||
* @return 原始类型 Class
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
fun getRawType(): Class<T> {
|
||||
var rawType: Type = type
|
||||
|
||||
// 如果是参数化类型,则提取原始类型部分
|
||||
if (type is ParameterizedType) {
|
||||
rawType = (type as ParameterizedType).rawType
|
||||
}
|
||||
// 如果是参数化类型,则提取原始类型部分
|
||||
if (type is ParameterizedType) {
|
||||
rawType = (type as ParameterizedType).rawType
|
||||
}
|
||||
|
||||
if (rawType is Class<*>) {
|
||||
return rawType as Class<T>
|
||||
}
|
||||
if (rawType is Class<*>) {
|
||||
return rawType as Class<T>
|
||||
}
|
||||
|
||||
throw IllegalStateException("无法获取原始类型: $type")
|
||||
}
|
||||
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
|
||||
val that = other as JsonTypeReference<*>
|
||||
/**
|
||||
* 判断两个 JsonTypeReference 实例是否相等
|
||||
* @param other 另一个对象
|
||||
* @return 是否相等
|
||||
*/
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other == null || this.javaClass != other.javaClass) return false
|
||||
val that = other as JsonTypeReference<*>
|
||||
|
||||
// 对于 ParameterizedType,需要更完整的比较
|
||||
if (this.type is ParameterizedType && that.type is ParameterizedType) {
|
||||
val thisParamType = this.type as ParameterizedType
|
||||
val thatParamType = that.type as ParameterizedType
|
||||
// 对于 ParameterizedType,需要更完整的比较
|
||||
if (this.type is ParameterizedType && that.type is ParameterizedType) {
|
||||
val thisParamType = this.type as ParameterizedType
|
||||
val thatParamType = that.type as ParameterizedType
|
||||
|
||||
return (
|
||||
Objects.equals(
|
||||
thisParamType.rawType,
|
||||
thatParamType.rawType
|
||||
) &&
|
||||
thisParamType.actualTypeArguments.contentEquals(thatParamType.actualTypeArguments) &&
|
||||
Objects.equals(
|
||||
thisParamType.ownerType,
|
||||
thatParamType.ownerType
|
||||
)
|
||||
)
|
||||
}
|
||||
return (
|
||||
Objects.equals(
|
||||
thisParamType.rawType,
|
||||
thatParamType.rawType
|
||||
) &&
|
||||
thisParamType.actualTypeArguments.contentEquals(thatParamType.actualTypeArguments) &&
|
||||
Objects.equals(
|
||||
thisParamType.ownerType,
|
||||
thatParamType.ownerType
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return Objects.equals(type, that.type)
|
||||
}
|
||||
return Objects.equals(type, that.type)
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算当前实例的哈希码
|
||||
* @return 哈希码值
|
||||
*/
|
||||
override fun hashCode(): Int {
|
||||
if (type is ParameterizedType) {
|
||||
val paramType = type as ParameterizedType
|
||||
return Objects.hash(
|
||||
paramType.rawType,
|
||||
paramType.actualTypeArguments.contentHashCode(),
|
||||
paramType.ownerType
|
||||
)
|
||||
}
|
||||
return Objects.hash(type)
|
||||
}
|
||||
/**
|
||||
* 计算当前实例的哈希码
|
||||
* @return 哈希码值
|
||||
*/
|
||||
override fun hashCode(): Int {
|
||||
if (type is ParameterizedType) {
|
||||
val paramType = type as ParameterizedType
|
||||
return Objects.hash(
|
||||
paramType.rawType,
|
||||
paramType.actualTypeArguments.contentHashCode(),
|
||||
paramType.ownerType
|
||||
)
|
||||
}
|
||||
return Objects.hash(type)
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回当前实例的字符串表示形式
|
||||
* @return 字符串描述
|
||||
*/
|
||||
override fun toString(): String {
|
||||
return "com.mingliqiye.utils.json.JsonTypeReference<${TypeReference.getRawString(type)}>"
|
||||
}
|
||||
/**
|
||||
* 返回当前实例的字符串表示形式
|
||||
* @return 字符串描述
|
||||
*/
|
||||
override fun toString(): String {
|
||||
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())
|
||||
}
|
||||
/**
|
||||
* 比较当前实例与另一个实例的大小关系
|
||||
* @param other 另一个 JsonTypeReference 实例
|
||||
* @return 比较结果
|
||||
*/
|
||||
override fun compareTo(other: JsonTypeReference<T>): Int {
|
||||
return this.type.toString().compareTo(other.type.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,11 +36,11 @@ import java.util.*
|
||||
* @return 如果类型匹配则返回 true,否则返回 false
|
||||
*/
|
||||
fun isTypeOf(type: Type, expectedClass: Class<*>): Boolean {
|
||||
return when (type) {
|
||||
is Class<*> -> expectedClass.isAssignableFrom(type)
|
||||
is ParameterizedType -> isTypeOf(type.rawType, expectedClass)
|
||||
else -> false
|
||||
}
|
||||
return when (type) {
|
||||
is Class<*> -> expectedClass.isAssignableFrom(type)
|
||||
is ParameterizedType -> isTypeOf(type.rawType, expectedClass)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,15 +52,15 @@ fun isTypeOf(type: Type, expectedClass: Class<*>): Boolean {
|
||||
* @throws IllegalArgumentException 当无法获取指定索引的泛型参数时抛出异常
|
||||
*/
|
||||
fun getGenericParameter(type: Type, index: Int): Type {
|
||||
if (type is ParameterizedType) {
|
||||
val typeArgs = type.actualTypeArguments
|
||||
if (index >= 0 && index < typeArgs.size) {
|
||||
return typeArgs[index]
|
||||
}
|
||||
}
|
||||
throw IllegalArgumentException(
|
||||
"无法获取泛型参数: $type at index $index"
|
||||
)
|
||||
if (type is ParameterizedType) {
|
||||
val typeArgs = type.actualTypeArguments
|
||||
if (index >= 0 && index < typeArgs.size) {
|
||||
return typeArgs[index]
|
||||
}
|
||||
}
|
||||
throw IllegalArgumentException(
|
||||
"无法获取泛型参数: $type at index $index"
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,24 +70,24 @@ fun getGenericParameter(type: Type, index: Int): Type {
|
||||
* @return 类型名称字符串
|
||||
*/
|
||||
fun getTypeName(type: Type): String {
|
||||
return when (type) {
|
||||
is Class<*> -> type.simpleName
|
||||
is ParameterizedType -> {
|
||||
val rawType = type.rawType as Class<*>
|
||||
val typeArgs = type.actualTypeArguments
|
||||
return when (type) {
|
||||
is Class<*> -> type.simpleName
|
||||
is ParameterizedType -> {
|
||||
val rawType = type.rawType as Class<*>
|
||||
val typeArgs = type.actualTypeArguments
|
||||
|
||||
val sb = StringBuilder(rawType.simpleName)
|
||||
sb.append("<")
|
||||
for (i in typeArgs.indices) {
|
||||
if (i > 0) sb.append(", ")
|
||||
sb.append(getTypeName(typeArgs[i]))
|
||||
}
|
||||
sb.append(">")
|
||||
sb.toString()
|
||||
}
|
||||
val sb = StringBuilder(rawType.simpleName)
|
||||
sb.append("<")
|
||||
for (i in typeArgs.indices) {
|
||||
if (i > 0) sb.append(", ")
|
||||
sb.append(getTypeName(typeArgs[i]))
|
||||
}
|
||||
sb.append(">")
|
||||
sb.toString()
|
||||
}
|
||||
|
||||
else -> type.typeName
|
||||
}
|
||||
else -> type.typeName
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,28 +98,28 @@ fun getTypeName(type: Type): String {
|
||||
* @return 表示数组类型的 JsonTypeReference 对象
|
||||
*/
|
||||
fun <T> arrayType(componentType: Class<T>): JsonTypeReference<Array<T>> {
|
||||
return object : JsonTypeReference<Array<T>>() {
|
||||
private val arrayType: Type = java.lang.reflect.Array.newInstance(
|
||||
componentType, 0
|
||||
).javaClass
|
||||
return object : JsonTypeReference<Array<T>>() {
|
||||
private val arrayType: Type = java.lang.reflect.Array.newInstance(
|
||||
componentType, 0
|
||||
).javaClass
|
||||
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
private val actualTypeArguments = arrayOf<Type>(componentType)
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
private val actualTypeArguments = arrayOf<Type>(componentType)
|
||||
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return actualTypeArguments
|
||||
}
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return actualTypeArguments
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return arrayType
|
||||
}
|
||||
override fun getRawType(): Type {
|
||||
return arrayType
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,22 +132,22 @@ fun <T> arrayType(componentType: Class<T>): JsonTypeReference<Array<T>> {
|
||||
*/
|
||||
fun <T> listType(componentType: Class<T>): JsonTypeReference<List<T>> {
|
||||
|
||||
return object : JsonTypeReference<List<T>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(componentType)
|
||||
}
|
||||
return object : JsonTypeReference<List<T>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(componentType)
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return List::class.java
|
||||
}
|
||||
override fun getRawType(): Type {
|
||||
return List::class.java
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,40 +162,40 @@ fun <T> listType(componentType: Class<T>): JsonTypeReference<List<T>> {
|
||||
*/
|
||||
fun <K, V> MapType(keyType: Class<K>, valueType: Class<V>): JsonTypeReference<Map<K, V>> {
|
||||
|
||||
return object : JsonTypeReference<Map<K, V>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(keyType, valueType)
|
||||
}
|
||||
return object : JsonTypeReference<Map<K, V>>() {
|
||||
override var type: Type = Any::class.java
|
||||
get() = object : ParameterizedType {
|
||||
override fun getActualTypeArguments(): Array<Type> {
|
||||
return arrayOf(keyType, valueType)
|
||||
}
|
||||
|
||||
override fun getRawType(): Type {
|
||||
return Map::class.java
|
||||
}
|
||||
override fun getRawType(): Type {
|
||||
return Map::class.java
|
||||
}
|
||||
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
override fun getOwnerType(): Type? {
|
||||
return null
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is ParameterizedType) return false
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is ParameterizedType) return false
|
||||
|
||||
val that = other
|
||||
return (Objects.equals(
|
||||
rawType,
|
||||
that.rawType
|
||||
) && actualTypeArguments.contentEquals(that.actualTypeArguments) && Objects.equals(
|
||||
ownerType,
|
||||
that.ownerType
|
||||
))
|
||||
}
|
||||
val that = other
|
||||
return (Objects.equals(
|
||||
rawType,
|
||||
that.rawType
|
||||
) && actualTypeArguments.contentEquals(that.actualTypeArguments) && Objects.equals(
|
||||
ownerType,
|
||||
that.ownerType
|
||||
))
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return (actualTypeArguments.contentHashCode() xor Objects.hashCode(rawType) xor Objects.hashCode(
|
||||
ownerType
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun hashCode(): Int {
|
||||
return (actualTypeArguments.contentHashCode() xor Objects.hashCode(rawType) xor Objects.hashCode(
|
||||
ownerType
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,67 +28,67 @@ import java.lang.reflect.Type
|
||||
import java.lang.reflect.WildcardType
|
||||
|
||||
class TypeReference(
|
||||
val rawClass: Type,
|
||||
vararg paramType: Type
|
||||
val rawClass: Type,
|
||||
vararg paramType: Type,
|
||||
) : ParameterizedType {
|
||||
|
||||
private val typeArguments: Array<out Type> = paramType
|
||||
override fun getActualTypeArguments(): Array<out Type> = typeArguments
|
||||
private val typeArguments: Array<out Type> = paramType
|
||||
override fun getActualTypeArguments(): Array<out Type> = typeArguments
|
||||
|
||||
override fun getRawType(): Type = rawClass
|
||||
override fun getRawType(): Type = rawClass
|
||||
|
||||
override fun getOwnerType(): Type? = null
|
||||
override fun getOwnerType(): Type? = null
|
||||
|
||||
|
||||
override fun toString(): String = "${getRawString(rawClass)}<${
|
||||
",".join(typeArguments) { getRawString(it) }
|
||||
}>"
|
||||
override fun toString(): String = "${getRawString(rawClass)}<${
|
||||
",".join(typeArguments) { getRawString(it) }
|
||||
}>"
|
||||
|
||||
companion object {
|
||||
companion object {
|
||||
|
||||
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])}"
|
||||
}
|
||||
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])}"
|
||||
}
|
||||
lowerBounds.isNotEmpty() -> {
|
||||
"? super ${getRawString(lowerBounds[0])}"
|
||||
}
|
||||
|
||||
else -> "?"
|
||||
}
|
||||
}
|
||||
else -> "?"
|
||||
}
|
||||
}
|
||||
|
||||
is ParameterizedType -> {
|
||||
of(type).toString()
|
||||
}
|
||||
is ParameterizedType -> {
|
||||
of(type).toString()
|
||||
}
|
||||
|
||||
else -> type.typeName
|
||||
}
|
||||
}
|
||||
else -> type.typeName
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T> of(): TypeReference {
|
||||
return of((object : JsonTypeReference<T>() {}).type)
|
||||
}
|
||||
inline fun <reified T> of(): TypeReference {
|
||||
return of((object : JsonTypeReference<T>() {}).type)
|
||||
}
|
||||
|
||||
fun of(type: Type): TypeReference {
|
||||
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)
|
||||
}
|
||||
fun of(type: Type): TypeReference {
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> throw IllegalStateException("无法获取类型: $type")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,73 +40,73 @@ import com.mingliqiye.utils.time.Formatter
|
||||
class DateTimeJsonConverter private constructor() : BaseJsonStringConverter<DateTime> {
|
||||
|
||||
|
||||
companion object {
|
||||
private val dateTimeJsonConverter by lazy {
|
||||
DateTimeJsonConverter()
|
||||
}
|
||||
companion object {
|
||||
private val dateTimeJsonConverter by lazy {
|
||||
DateTimeJsonConverter()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getJsonConverter(): DateTimeJsonConverter = dateTimeJsonConverter
|
||||
}
|
||||
@JvmStatic
|
||||
fun getJsonConverter(): DateTimeJsonConverter = dateTimeJsonConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 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
|
||||
/**
|
||||
* 将 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>()
|
||||
// 获取 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()
|
||||
}
|
||||
}
|
||||
// 根据注解中的格式化规则进行转换
|
||||
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
|
||||
/**
|
||||
* 将 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>()
|
||||
// 获取 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 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>()
|
||||
/**
|
||||
* 获取当前转换器支持的目标类型引用。
|
||||
*
|
||||
* @return 返回 DateTime 类型的 JsonTypeReference。
|
||||
* @throws Exception 如果在获取类型引用时发生异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getFromType(): JsonTypeReference<DateTime> = JsonTypeReference.of<DateTime>()
|
||||
}
|
||||
|
||||
@@ -40,71 +40,71 @@ import com.mingliqiye.utils.uuid.UUIDFormatType
|
||||
*/
|
||||
class UUIDJsonConverter private constructor() : BaseJsonStringConverter<UUID> {
|
||||
|
||||
companion object {
|
||||
private val uuidJsonConverter by lazy {
|
||||
UUIDJsonConverter()
|
||||
}
|
||||
companion object {
|
||||
private val uuidJsonConverter by lazy {
|
||||
UUIDJsonConverter()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getJsonConverter(): UUIDJsonConverter = uuidJsonConverter
|
||||
}
|
||||
@JvmStatic
|
||||
fun getJsonConverter(): UUIDJsonConverter = uuidJsonConverter
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 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
|
||||
/**
|
||||
* 将 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()
|
||||
// 获取 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()
|
||||
}
|
||||
}
|
||||
// 根据注解中的 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
|
||||
/**
|
||||
* 将字符串反序列化为 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)
|
||||
// 获取 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)
|
||||
}
|
||||
}
|
||||
// 根据注解中的 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>()
|
||||
/**
|
||||
* 返回当前转换器支持的目标类型引用。
|
||||
*
|
||||
* @return 表示 UUID 类型的 JsonTypeReference 对象。
|
||||
*/
|
||||
override fun getFromType() = JsonTypeReference.of<UUID>()
|
||||
}
|
||||
|
||||
@@ -27,56 +27,56 @@ package com.mingliqiye.utils.json.converters.base
|
||||
* 提供了一个通用方法来根据注解类型获取对应的注解实例。
|
||||
*/
|
||||
interface AnnotationGetter {
|
||||
/**
|
||||
* 根据指定的注解类型获取该类型的注解实例。
|
||||
*
|
||||
* @param clazz 注解的Class对象,表示要获取的注解类型。
|
||||
* @return 返回对应类型的注解实例,如果未找到则返回null。
|
||||
*/
|
||||
fun <T : Annotation> get(clazz: Class<T>): T?
|
||||
/**
|
||||
* 根据指定的注解类型获取该类型的注解实例。
|
||||
*
|
||||
* @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)
|
||||
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
|
||||
}
|
||||
/**
|
||||
* 提供一个默认实现,始终返回null。
|
||||
* 可用于需要空注解获取器的场景。
|
||||
*/
|
||||
val nullGetter = object : AnnotationGetter {
|
||||
/**
|
||||
* 始终返回null,不执行任何实际逻辑。
|
||||
*
|
||||
* @param clazz 注解的Class对象(未使用)。
|
||||
* @return 始终返回null。
|
||||
*/
|
||||
override fun <T : Annotation> get(clazz: Class<T>): T? = null
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建一个AnnotationGetter对象,用于根据指定的注解类型获取对应的注解实例。
|
||||
*
|
||||
* @param annotation 要包装的注解实例,作为内部逻辑的来源。
|
||||
* @return 返回一个实现了AnnotationGetter接口的匿名对象。
|
||||
*/
|
||||
fun oneGetter(annotation: Annotation) = object : AnnotationGetter {
|
||||
/**
|
||||
* 根据传入的注解类型clazz,尝试返回与annotation匹配的注解实例。
|
||||
*
|
||||
* @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
|
||||
}
|
||||
/**
|
||||
* 创建一个AnnotationGetter对象,用于根据指定的注解类型获取对应的注解实例。
|
||||
*
|
||||
* @param annotation 要包装的注解实例,作为内部逻辑的来源。
|
||||
* @return 返回一个实现了AnnotationGetter接口的匿名对象。
|
||||
*/
|
||||
fun oneGetter(annotation: Annotation) = object : AnnotationGetter {
|
||||
/**
|
||||
* 根据传入的注解类型clazz,尝试返回与annotation匹配的注解实例。
|
||||
*
|
||||
* @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
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -35,15 +35,15 @@ import java.math.BigDecimal
|
||||
*/
|
||||
interface BaseJsonBigDecimalConverter<E> : BaseJsonConverter<E, BigDecimal> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [BigDecimal]。
|
||||
* 通过调用 [JsonTypeReference.Companion.of] 方法创建类型引用。
|
||||
*
|
||||
* @return 目标类型 [BigDecimal] 的类型引用。
|
||||
* @throws Exception 如果在获取类型引用时发生异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<BigDecimal>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [BigDecimal]。
|
||||
* 通过调用 [JsonTypeReference.Companion.of] 方法创建类型引用。
|
||||
*
|
||||
* @return 目标类型 [BigDecimal] 的类型引用。
|
||||
* @throws Exception 如果在获取类型引用时发生异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<BigDecimal>()
|
||||
}
|
||||
|
||||
+9
-9
@@ -33,13 +33,13 @@ import java.math.BigInteger
|
||||
*/
|
||||
interface BaseJsonBigIntegerConverter<E> : BaseJsonConverter<E, BigInteger> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用,用于 JSON 反序列化时确定目标类型。
|
||||
* 该方法重写了父接口中的 [getToType] 方法,并返回 `BigInteger` 类型的引用。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 对象,表示 `BigInteger` 类型的引用。
|
||||
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<BigInteger>()
|
||||
/**
|
||||
* 获取目标类型的引用,用于 JSON 反序列化时确定目标类型。
|
||||
* 该方法重写了父接口中的 [getToType] 方法,并返回 `BigInteger` 类型的引用。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 对象,表示 `BigInteger` 类型的引用。
|
||||
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<BigInteger>()
|
||||
}
|
||||
|
||||
+11
-11
@@ -32,15 +32,15 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
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>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法返回一个 [JsonTypeReference] 对象,表示目标类型为 [Boolean]。
|
||||
* 此方法重写了父接口中的定义,并通过 [JsonTypeReference.Companion.of] 方法获取布尔类型的引用。
|
||||
*
|
||||
* @return [JsonTypeReference<Boolean>] 表示布尔类型的引用。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Boolean>()
|
||||
}
|
||||
|
||||
@@ -32,12 +32,12 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
* @param E 泛型参数,表示需要转换的目标对象类型。
|
||||
*/
|
||||
interface BaseJsonByteConverter<E> : BaseJsonConverter<E, Byte> {
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识转换的目标类型为 Byte。
|
||||
*
|
||||
* @return 返回 JsonTypeReference 类型的实例,表示目标类型为 Byte。
|
||||
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Byte>()
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识转换的目标类型为 Byte。
|
||||
*
|
||||
* @return 返回 JsonTypeReference 类型的实例,表示目标类型为 Byte。
|
||||
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Byte>()
|
||||
}
|
||||
|
||||
+8
-8
@@ -31,12 +31,12 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
interface BaseJsonDoubleConverter<E> : BaseJsonConverter<E, Double> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识转换的目标类型为 Double。
|
||||
*
|
||||
* @return 返回 JsonTypeReference<Double> 类型的实例,表示目标类型为 Double。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Double>()
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识转换的目标类型为 Double。
|
||||
*
|
||||
* @return 返回 JsonTypeReference<Double> 类型的实例,表示目标类型为 Double。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Double>()
|
||||
}
|
||||
|
||||
+11
-11
@@ -32,15 +32,15 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
interface BaseJsonFloatConverter<E> : BaseJsonConverter<E, Float> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回 [Float] 类型的 [JsonTypeReference] 实例。
|
||||
* 用于标识当前转换器的目标类型为 [Float]。
|
||||
*
|
||||
* @return [JsonTypeReference] 表示 [Float] 类型的引用信息。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Float>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回 [Float] 类型的 [JsonTypeReference] 实例。
|
||||
* 用于标识当前转换器的目标类型为 [Float]。
|
||||
*
|
||||
* @return [JsonTypeReference] 表示 [Float] 类型的引用信息。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Float>()
|
||||
}
|
||||
|
||||
@@ -32,15 +32,15 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
interface BaseJsonIntConverter<E> : BaseJsonConverter<E, Int> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回 [Int] 类型的 [JsonTypeReference] 实例。
|
||||
* 用于标识当前转换器的目标类型为 [Int]。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Int]。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Int>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回 [Int] 类型的 [JsonTypeReference] 实例。
|
||||
* 用于标识当前转换器的目标类型为 [Int]。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Int]。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Int>()
|
||||
}
|
||||
|
||||
@@ -32,12 +32,12 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
interface BaseJsonLongConverter<E> : BaseJsonConverter<E, Long> {
|
||||
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识此转换器的目标类型为 [Long]。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Long]。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Long>()
|
||||
/**
|
||||
* 获取目标类型的引用,用于标识此转换器的目标类型为 [Long]。
|
||||
*
|
||||
* @return 返回 [JsonTypeReference] 的实例,表示目标类型为 [Long]。
|
||||
* @throws Exception 如果在获取类型引用时发生异常,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Long>()
|
||||
}
|
||||
|
||||
+11
-11
@@ -32,15 +32,15 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
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>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回 [Short] 类型的 [JsonTypeReference] 实例。
|
||||
* 通过 [JsonTypeReference.Companion.of] 方法创建类型引用。
|
||||
*
|
||||
* @return [JsonTypeReference] 表示 [Short] 类型的引用。
|
||||
* @throws Exception 如果在获取类型引用过程中发生异常,则抛出该异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<Short>()
|
||||
}
|
||||
|
||||
+11
-11
@@ -32,15 +32,15 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
*/
|
||||
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>()
|
||||
/**
|
||||
* 获取目标类型的引用信息。
|
||||
*
|
||||
* 该方法重写了父接口中的 [getToType] 方法,返回一个表示 [String] 类型的 [JsonTypeReference] 实例。
|
||||
* 此方法可能抛出异常,因此使用 [@Throws(Exception::class)] 注解标记。
|
||||
*
|
||||
* @return 返回一个 [JsonTypeReference] 实例,表示目标类型为 [String]。
|
||||
* @throws Exception 如果在获取类型引用时发生错误,则抛出此异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
override fun getToType() = JsonTypeReference.of<String>()
|
||||
}
|
||||
|
||||
+24
-24
@@ -30,33 +30,33 @@ import tools.jackson.databind.ValueDeserializer
|
||||
|
||||
|
||||
class JackJson3Deserializer<F, T>(
|
||||
val property: BeanProperty? = null,
|
||||
val jsonConverter: JsonConverter<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)
|
||||
})
|
||||
}
|
||||
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)
|
||||
}
|
||||
/**
|
||||
* 上下文感知方法:设置当前属性信息。
|
||||
*
|
||||
* @param ctxt 反序列化上下文,可选参数。
|
||||
* @param property 当前属性信息。
|
||||
* @return 返回当前反序列化器实例。
|
||||
*/
|
||||
override fun createContextual(
|
||||
ctxt: DeserializationContext?,
|
||||
property: BeanProperty?,
|
||||
): JackJson3Deserializer<F, T> {
|
||||
return JackJson3Deserializer(property, jsonConverter)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -29,38 +29,38 @@ import java.math.BigDecimal
|
||||
import java.math.BigInteger
|
||||
|
||||
class JackJson3Serializer<F, T>(
|
||||
val property: BeanProperty? = null,
|
||||
val jsonConverter: JsonConverter<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")
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 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)
|
||||
}
|
||||
override fun createContextual(ctxt: SerializationContext?, property: BeanProperty?): ValueSerializer<*> {
|
||||
return JackJson3Serializer(property, jsonConverter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,30 +30,30 @@ import com.fasterxml.jackson.databind.JsonDeserializer
|
||||
import com.fasterxml.jackson.databind.deser.ContextualDeserializer
|
||||
|
||||
class JackJsonDeserializer<F, T>(
|
||||
val property: BeanProperty? = null,
|
||||
val jsonConverter: JsonConverter<F, T>
|
||||
val property: BeanProperty? = null,
|
||||
val jsonConverter: JsonConverter<F, T>,
|
||||
) : JsonDeserializer<F>(), ContextualDeserializer {
|
||||
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)
|
||||
})
|
||||
}
|
||||
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?
|
||||
): JackJsonDeserializer<F, T> {
|
||||
return JackJsonDeserializer(property, jsonConverter)
|
||||
}
|
||||
/**
|
||||
* 上下文感知方法:设置当前属性信息。
|
||||
*
|
||||
* @param ctxt 反序列化上下文,可选参数。
|
||||
* @param property 当前属性信息。
|
||||
* @return 返回当前反序列化器实例。
|
||||
*/
|
||||
override fun createContextual(
|
||||
ctxt: DeserializationContext?,
|
||||
property: BeanProperty?,
|
||||
): JackJsonDeserializer<F, T> {
|
||||
return JackJsonDeserializer(property, jsonConverter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,55 +31,55 @@ import java.math.BigDecimal
|
||||
import java.math.BigInteger
|
||||
|
||||
class JackJsonSerializer<F, T>(
|
||||
val property: BeanProperty?,
|
||||
val jsonConverter: JsonConverter<F, T>
|
||||
val property: BeanProperty?,
|
||||
val jsonConverter: JsonConverter<F, T>,
|
||||
) : JsonSerializer<F>(), ContextualSerializer {
|
||||
|
||||
/**
|
||||
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
|
||||
*
|
||||
* @param value 源对象,可能为 null。
|
||||
* @param gen JSON 生成器,用于写入 JSON 数据。
|
||||
* @param provider 序列化提供者,可选参数。
|
||||
*/
|
||||
override fun serialize(
|
||||
value: F?,
|
||||
gen: JsonGenerator,
|
||||
provider: SerializerProvider?
|
||||
) {
|
||||
// 执行转换逻辑
|
||||
val data: T? = jsonConverter.convert(value, object : AnnotationGetter {
|
||||
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
|
||||
})
|
||||
/**
|
||||
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
|
||||
*
|
||||
* @param value 源对象,可能为 null。
|
||||
* @param gen JSON 生成器,用于写入 JSON 数据。
|
||||
* @param provider 序列化提供者,可选参数。
|
||||
*/
|
||||
override fun serialize(
|
||||
value: F?,
|
||||
gen: JsonGenerator,
|
||||
provider: SerializerProvider?,
|
||||
) {
|
||||
// 执行转换逻辑
|
||||
val data: T? = jsonConverter.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")
|
||||
}
|
||||
}
|
||||
// 根据目标对象的类型写入对应的 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> {
|
||||
return JackJsonSerializer(property, jsonConverter)
|
||||
}
|
||||
/**
|
||||
* 上下文感知方法:设置当前属性信息。
|
||||
*
|
||||
* @param prov 序列化提供者,可选参数。
|
||||
* @param property 当前属性信息。
|
||||
* @return 返回当前序列化器实例。
|
||||
*/
|
||||
override fun createContextual(
|
||||
prov: SerializerProvider?,
|
||||
property: BeanProperty?,
|
||||
): JsonSerializer<F> {
|
||||
return JackJsonSerializer(property, jsonConverter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,61 +31,61 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||
* @param T 目标类型,表示转换后的对象类型。
|
||||
*/
|
||||
interface JsonConverter<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 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?
|
||||
/**
|
||||
* 将目标对象反向转换为源对象。
|
||||
*
|
||||
* @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 getFromType(): JsonTypeReference<F>
|
||||
|
||||
/**
|
||||
* 获取目标类型的类型引用。
|
||||
*
|
||||
* @return 目标类型的 JsonTypeReference 对象。
|
||||
* @throws Exception 获取过程中可能抛出的异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
fun getToType(): JsonTypeReference<T>
|
||||
/**
|
||||
* 获取目标类型的类型引用。
|
||||
*
|
||||
* @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 getFromClass() = getFromType().getRawType()
|
||||
|
||||
/**
|
||||
* 获取目标类型的原始类。
|
||||
*
|
||||
* @return 目标类型的 Class 对象。
|
||||
* @throws Exception 获取过程中可能抛出的异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
fun getToClass() = getToType().getRawType()
|
||||
/**
|
||||
* 获取目标类型的原始类。
|
||||
*
|
||||
* @return 目标类型的 Class 对象。
|
||||
* @throws Exception 获取过程中可能抛出的异常。
|
||||
*/
|
||||
@Throws(Exception::class)
|
||||
fun getToClass() = getToType().getRawType()
|
||||
}
|
||||
|
||||
@@ -37,36 +37,36 @@ val log = MingLiLoggerFactory.getLogger("com.mingliqiye.utils.json.converters.ba
|
||||
* @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
|
||||
}
|
||||
return clazz
|
||||
// 尝试将type直接转换为Class类型,如果失败则检查是否为ParameterizedType
|
||||
val clazz: Class<*>? = type as? Class<*> ?: if (type is ParameterizedType) {
|
||||
// 如果是ParameterizedType,则递归获取其原始类型
|
||||
getClass(type.rawType)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
return clazz
|
||||
}
|
||||
|
||||
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(
|
||||
"getJsonConverter"
|
||||
).invoke(null) as T
|
||||
} catch (e: Exception) {
|
||||
log.error("实现于 JsonConverter<*, *> 的类 必须实现静态方法 JsonConverter<*, *> getJsonConverter()", e)
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
return clazz.getDeclaredMethod(
|
||||
"getJsonConverter"
|
||||
).invoke(null) as T
|
||||
} catch (e: Exception) {
|
||||
log.error("实现于 JsonConverter<*, *> 的类 必须实现静态方法 JsonConverter<*, *> getJsonConverter()", e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun <T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(clazz: Class<T>): com.fasterxml.jackson.databind.ObjectMapper =
|
||||
this.registerModule(getJsonConverter(clazz).getJacksonModule())
|
||||
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())
|
||||
this.registerModule(getJsonConverter(T::class.java).getJacksonModule())
|
||||
|
||||
/**
|
||||
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
|
||||
@@ -74,11 +74,11 @@ inline fun <reified T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.
|
||||
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
|
||||
*/
|
||||
fun <F, T> JsonConverter<F, T>.getJacksonModule(): com.fasterxml.jackson.databind.module.SimpleModule =
|
||||
com.fasterxml.jackson.databind.module.SimpleModule("(${getFromClass().name})-(${getToClass().name})")
|
||||
.addSerializer(getFromClass(), JackJsonSerializer(null, this))
|
||||
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this))
|
||||
com.fasterxml.jackson.databind.module.SimpleModule("(${getFromClass().name})-(${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})-(${getToClass().name})")
|
||||
.addSerializer(getFromClass(), JackJson3Serializer(null, this))
|
||||
.addDeserializer(getFromClass(), JackJson3Deserializer(null, this))
|
||||
tools.jackson.databind.module.SimpleModule("(${getFromClass().name})-(${getToClass().name})")
|
||||
.addSerializer(getFromClass(), JackJson3Serializer(null, this))
|
||||
.addDeserializer(getFromClass(), JackJson3Deserializer(null, this))
|
||||
|
||||
@@ -30,146 +30,146 @@ import java.util.*
|
||||
* JSON 元素接口,定义所有 JSON 数据类型的通用操作
|
||||
*/
|
||||
interface JsonItem {
|
||||
/**
|
||||
* 作为 JSON 对象返回
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun asObject(): JsonObject {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
/**
|
||||
* 作为 JSON 对象返回
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun asObject(): JsonObject {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
|
||||
/**
|
||||
* 作为 JSON 数组返回
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun asArray(): JsonArray {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
/**
|
||||
* 作为 JSON 数组返回
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun asArray(): JsonArray {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
|
||||
/**
|
||||
* 作为字符串返回
|
||||
* @throws IllegalStateException 如果不是字符串类型
|
||||
*/
|
||||
fun asString(): String {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a String")
|
||||
}
|
||||
/**
|
||||
* 作为字符串返回
|
||||
* @throws IllegalStateException 如果不是字符串类型
|
||||
*/
|
||||
fun asString(): String {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a String")
|
||||
}
|
||||
|
||||
/**
|
||||
* 作为布尔值返回
|
||||
* @throws IllegalStateException 如果不是布尔类型
|
||||
*/
|
||||
fun asBoolean(): Boolean {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Boolean")
|
||||
}
|
||||
/**
|
||||
* 作为布尔值返回
|
||||
* @throws IllegalStateException 如果不是布尔类型
|
||||
*/
|
||||
fun asBoolean(): Boolean {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Boolean")
|
||||
}
|
||||
|
||||
/**
|
||||
* 作为数字返回
|
||||
* @throws IllegalStateException 如果不是数字类型
|
||||
*/
|
||||
fun asNumber(): JsonNumber {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Number")
|
||||
}
|
||||
/**
|
||||
* 作为数字返回
|
||||
* @throws IllegalStateException 如果不是数字类型
|
||||
*/
|
||||
fun asNumber(): JsonNumber {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Number")
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为 List 集合
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun toList(): List<JsonItem> {
|
||||
val it = asArray().iteratorArray()
|
||||
val list = LinkedList<JsonItem>()
|
||||
it.forEach { item -> list.add(item.value) }
|
||||
return list
|
||||
}
|
||||
/**
|
||||
* 转换为 List 集合
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun toList(): List<JsonItem> {
|
||||
val it = asArray().iteratorArray()
|
||||
val list = LinkedList<JsonItem>()
|
||||
it.forEach { item -> list.add(item.value) }
|
||||
return list
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为 Map 集合
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun toMap(): Map<String, JsonItem> {
|
||||
val it = asObject().iteratorObject()
|
||||
val map = LinkedHashMap<String, JsonItem>()
|
||||
it.forEach { item -> map[item.key] = item.value }
|
||||
return map
|
||||
}
|
||||
/**
|
||||
* 转换为 Map 集合
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun toMap(): Map<String, JsonItem> {
|
||||
val it = asObject().iteratorObject()
|
||||
val map = LinkedHashMap<String, JsonItem>()
|
||||
it.forEach { item -> map[item.key] = item.value }
|
||||
return map
|
||||
}
|
||||
|
||||
/** 是否为 null */
|
||||
fun isNull(): Boolean = false
|
||||
/** 是否为 null */
|
||||
fun isNull(): Boolean = false
|
||||
|
||||
/** 是否为布尔值 */
|
||||
fun isBoolean(): Boolean = false
|
||||
/** 是否为布尔值 */
|
||||
fun isBoolean(): Boolean = false
|
||||
|
||||
/** 是否为数字 */
|
||||
fun isNumber(): Boolean = false
|
||||
/** 是否为数字 */
|
||||
fun isNumber(): Boolean = false
|
||||
|
||||
/** 是否为字符串 */
|
||||
fun isString(): Boolean = false
|
||||
/** 是否为字符串 */
|
||||
fun isString(): Boolean = false
|
||||
|
||||
/** 是否为对象 */
|
||||
fun isObject(): Boolean = false
|
||||
/** 是否为对象 */
|
||||
fun isObject(): Boolean = false
|
||||
|
||||
/** 是否为数组 */
|
||||
fun isArray(): Boolean = false
|
||||
/** 是否为数组 */
|
||||
fun isArray(): Boolean = false
|
||||
|
||||
/** 返回当前元素的类型名称 */
|
||||
fun name(): String = "Any"
|
||||
/** 返回当前元素的类型名称 */
|
||||
fun name(): String = "Any"
|
||||
|
||||
/** 根据索引获取元素(数组专用) */
|
||||
fun get(index: Int): JsonItem = getIndex(index)
|
||||
/** 根据索引获取元素(数组专用) */
|
||||
fun get(index: Int): JsonItem = getIndex(index)
|
||||
|
||||
/** 根据字段名获取元素(对象专用) */
|
||||
fun get(fieldName: String): JsonItem = getField(fieldName)
|
||||
/** 根据字段名获取元素(对象专用) */
|
||||
fun get(fieldName: String): JsonItem = getField(fieldName)
|
||||
|
||||
/**
|
||||
* 根据索引获取元素
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun getIndex(index: Int): JsonItem {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
/**
|
||||
* 根据索引获取元素
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun getIndex(index: Int): JsonItem {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据字段名获取元素
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun getField(name: String): JsonItem {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
/**
|
||||
* 根据字段名获取元素
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun getField(name: String): JsonItem {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历数组元素
|
||||
* @param consumer 接收索引和元素的消费者函数
|
||||
*/
|
||||
fun forEachArray(consumer: (Int, JsonItem) -> Unit) {
|
||||
iteratorArray().forEach {
|
||||
consumer(it.index, it.value)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 遍历数组元素
|
||||
* @param consumer 接收索引和元素的消费者函数
|
||||
*/
|
||||
fun forEachArray(consumer: (Int, JsonItem) -> Unit) {
|
||||
iteratorArray().forEach {
|
||||
consumer(it.index, it.value)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历对象字段
|
||||
* @param consumer 接收字段名和值的消费者函数
|
||||
*/
|
||||
fun forEachObject(consumer: (String, JsonItem) -> Unit) {
|
||||
iteratorObject().forEach {
|
||||
consumer(it.key, it.value)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 遍历对象字段
|
||||
* @param consumer 接收字段名和值的消费者函数
|
||||
*/
|
||||
fun forEachObject(consumer: (String, JsonItem) -> Unit) {
|
||||
iteratorObject().forEach {
|
||||
consumer(it.key, it.value)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数组迭代器
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
/**
|
||||
* 获取数组迭代器
|
||||
* @throws IllegalStateException 如果不是数组类型
|
||||
*/
|
||||
fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Array")
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取对象迭代器
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
/**
|
||||
* 获取对象迭代器
|
||||
* @throws IllegalStateException 如果不是对象类型
|
||||
*/
|
||||
fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
|
||||
throw IllegalStateException("Current JSON element is ${name()} not a Object")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,20 +177,20 @@ interface JsonItem {
|
||||
* 表示键值对形式的 JSON 对象 {}
|
||||
*/
|
||||
abstract class JsonObject : JsonItem {
|
||||
override fun isObject(): Boolean = true
|
||||
override fun name(): String = "object"
|
||||
override fun asObject(): JsonObject = this
|
||||
override fun toString(): String = StringBuilder().apply {
|
||||
append("{")
|
||||
iteratorObject().forEach {
|
||||
append(it.key)
|
||||
append("=")
|
||||
append(it.value)
|
||||
append(",")
|
||||
}
|
||||
deleteCharAt(length - 1)
|
||||
append("}")
|
||||
}.toString()
|
||||
override fun isObject(): Boolean = true
|
||||
override fun name(): String = "object"
|
||||
override fun asObject(): JsonObject = this
|
||||
override fun toString(): String = StringBuilder().apply {
|
||||
append("{")
|
||||
iteratorObject().forEach {
|
||||
append(it.key)
|
||||
append("=")
|
||||
append(it.value)
|
||||
append(",")
|
||||
}
|
||||
deleteCharAt(length - 1)
|
||||
append("}")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,18 +198,18 @@ abstract class JsonObject : JsonItem {
|
||||
* 表示有序的 JSON 数组 []
|
||||
*/
|
||||
abstract class JsonArray : JsonItem {
|
||||
override fun isArray(): Boolean = true
|
||||
override fun name(): String = "array"
|
||||
override fun asArray() = this
|
||||
override fun toString(): String = StringBuilder().apply {
|
||||
append("[")
|
||||
iteratorArray().forEach {
|
||||
append(it.value)
|
||||
append(",")
|
||||
}
|
||||
deleteCharAt(length - 1)
|
||||
append("]")
|
||||
}.toString()
|
||||
override fun isArray(): Boolean = true
|
||||
override fun name(): String = "array"
|
||||
override fun asArray() = this
|
||||
override fun toString(): String = StringBuilder().apply {
|
||||
append("[")
|
||||
iteratorArray().forEach {
|
||||
append(it.value)
|
||||
append(",")
|
||||
}
|
||||
deleteCharAt(length - 1)
|
||||
append("]")
|
||||
}.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -217,9 +217,9 @@ abstract class JsonArray : JsonItem {
|
||||
* 表示 JSON 中的 null 值
|
||||
*/
|
||||
open class JsonNull : JsonItem {
|
||||
override fun isNull(): Boolean = true
|
||||
override fun name(): String = "null"
|
||||
override fun toString(): String = "null"
|
||||
override fun isNull(): Boolean = true
|
||||
override fun name(): String = "null"
|
||||
override fun toString(): String = "null"
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,26 +228,26 @@ open class JsonNull : JsonItem {
|
||||
* @param numberString 数字的字符串表示形式
|
||||
*/
|
||||
open class JsonNumber(val numberString: String) : JsonItem, Number() {
|
||||
override fun isNumber(): Boolean = true
|
||||
override fun name(): String = "number"
|
||||
override fun asNumber(): JsonNumber = this
|
||||
override fun toDouble(): Double = numberString.toDouble()
|
||||
override fun toFloat(): Float = numberString.toFloat()
|
||||
override fun toLong(): Long = numberString.toLong()
|
||||
override fun toInt(): Int = numberString.toInt()
|
||||
override fun toShort(): Short = numberString.toShort()
|
||||
override fun toByte(): Byte = numberString.toByte()
|
||||
override fun isNumber(): Boolean = true
|
||||
override fun name(): String = "number"
|
||||
override fun asNumber(): JsonNumber = this
|
||||
override fun toDouble(): Double = numberString.toDouble()
|
||||
override fun toFloat(): Float = numberString.toFloat()
|
||||
override fun toLong(): Long = numberString.toLong()
|
||||
override fun toInt(): Int = numberString.toInt()
|
||||
override fun toShort(): Short = numberString.toShort()
|
||||
override fun toByte(): Byte = numberString.toByte()
|
||||
|
||||
/** 转换为 BigDecimal */
|
||||
open fun toBigDecimal(): BigDecimal = numberString.toBigDecimal()
|
||||
/** 转换为 BigDecimal */
|
||||
open fun toBigDecimal(): BigDecimal = numberString.toBigDecimal()
|
||||
|
||||
/** 转换为指定精度的 BigDecimal */
|
||||
open fun toBigDecimal(scale: Int): BigDecimal = numberString.toBigDecimal().setScale(scale)
|
||||
/** 转换为指定精度的 BigDecimal */
|
||||
open fun toBigDecimal(scale: Int): BigDecimal = numberString.toBigDecimal().setScale(scale)
|
||||
|
||||
/** 转换为 BigInteger */
|
||||
open fun toBigInteger(): BigInteger = numberString.toBigInteger()
|
||||
/** 转换为 BigInteger */
|
||||
open fun toBigInteger(): BigInteger = numberString.toBigInteger()
|
||||
|
||||
override fun toString(): String = numberString
|
||||
override fun toString(): String = numberString
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -255,13 +255,13 @@ open class JsonNumber(val numberString: String) : JsonItem, Number() {
|
||||
* @param value 字符串值
|
||||
*/
|
||||
open class JsonString(val value: String) : JsonItem {
|
||||
override fun isString(): Boolean = true
|
||||
override fun name(): String = "string"
|
||||
override fun asString(): String {
|
||||
return value
|
||||
}
|
||||
override fun isString(): Boolean = true
|
||||
override fun name(): String = "string"
|
||||
override fun asString(): String {
|
||||
return value
|
||||
}
|
||||
|
||||
override fun toString(): String = value
|
||||
override fun toString(): String = value
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -269,11 +269,11 @@ open class JsonString(val value: String) : JsonItem {
|
||||
* @param value 布尔值
|
||||
*/
|
||||
open class JsonBoolean(val value: Boolean) : JsonItem {
|
||||
override fun isBoolean(): Boolean = true
|
||||
override fun name(): String = "boolean"
|
||||
override fun asBoolean(): Boolean {
|
||||
return value
|
||||
}
|
||||
override fun isBoolean(): Boolean = true
|
||||
override fun name(): String = "boolean"
|
||||
override fun asBoolean(): Boolean {
|
||||
return value
|
||||
}
|
||||
|
||||
override fun toString(): String = value.toString()
|
||||
override fun toString(): String = value.toString()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user