This commit is contained in:
2026-06-21 10:41:28 +08:00
parent e00f8ad7a1
commit 60ec0e2883
38 changed files with 23987 additions and 614 deletions
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JSONA.kt
* LastUpdate 2026-02-26 14:14:18
* LastUpdate 2026-03-18 09:14:06
* UpdateUser MingLiPro
*/
@@ -29,10 +29,13 @@ import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import com.mingliqiye.utils.json.objects.base.JsonItem
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Path
import kotlin.io.path.readBytes
/**
* JSON工具类,提供静态方法访问JSON API功能
@@ -263,7 +266,7 @@ object JSONA {
*/
@JvmStatic
fun <T> parse(
json: String, type: JsonTypeReference<T>, defaultValue: T
json: String, type: JsonTypeReference<T>, defaultValue: T,
): T = getJsonApi().parse(json, type, defaultValue)
/**
@@ -401,7 +404,7 @@ object JSONA {
*/
@JvmStatic
fun <K, V> parseMap(
json: String, keyType: Class<K>, valueType: Class<V>
json: String, keyType: Class<K>, valueType: Class<V>,
): MutableMap<K, V> = getJsonApi().parseMap(json, keyType, valueType)
/**
@@ -414,7 +417,7 @@ object JSONA {
*/
@JvmStatic
inline fun <reified K, reified V> parseMap(
json: String
json: String,
): MutableMap<K, V> = getJsonApi().parseMap(json, K::class.java, V::class.java)
/**
@@ -429,7 +432,6 @@ object JSONA {
/**
* 将对象转换为JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的JSON字节数组
*/
@JvmStatic
@@ -438,7 +440,6 @@ object JSONA {
/**
* 将对象转换为美化格式的JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的美化格式JSON字节数组
*/
@JvmStatic
@@ -478,7 +479,6 @@ object JSONA {
/**
* 将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationClass 目标对象的Class类型
@@ -490,7 +490,6 @@ object JSONA {
/**
* 使用内联函数和reified类型参数将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型(通过reified类型参数推断)
* @param source 需要转换的源对象
* @return 转换后的目标类型对象
@@ -501,7 +500,6 @@ object JSONA {
/**
* 将源对象转换为目标类型的对象,使用JsonTypeReference指定目标类型
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationType 目标对象的JsonTypeReference类型引用
@@ -540,4 +538,86 @@ object JSONA {
@JvmStatic
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
/**
* 将 JSON 字符串解析为 JsonItem 对象
*
* @param json JSON 格式的字符串
* @return 解析后的 JsonItem 对象,可以是 JsonObject、JsonArray 或 JsonValue
*/
@JvmStatic
fun parseJsonItem(json: String): JsonItem = getJsonApi().parseJsonItem(json)
/**
* 将字节数组解析为 JsonItem 对象
* 字节数组会被转换为字符串后再解析
*
* @param byte JSON 格式的字节数组(通常是 UTF-8 编码)
* @return 解析后的 JsonItem 对象
*/
@JvmStatic
fun parseJsonItem(byte: ByteArray): JsonItem {
return parseJsonItem(String(byte))
}
/**
* 将输入流解析为 JsonItem 对象
* 会自动关闭输入流
*
* @param inputStream JSON 数据的输入流
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取输入流失败时抛出
*
* 使用示例:
* ```
* val inputStream = FileInputStream("data.json")
* val jsonItem = converter.parseJsonItem(inputStream)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(inputStream: InputStream): JsonItem {
inputStream.use {
return parseJsonItem(it.readAllBytes())
}
}
/**
* 将文件解析为 JsonItem 对象
*
* @param file 包含 JSON 数据的文件
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val file = File("config.json")
* val jsonItem = converter.parseJsonItem(file)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(file: File): JsonItem {
return parseJsonItem(file.readBytes())
}
/**
* 将文件路径解析为 JsonItem 对象
*
* @param path 包含 JSON 数据的文件路径
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val path = Paths.get("data/user.json")
* val jsonItem = converter.parseJsonItem(path)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(path: Path): JsonItem {
return parseJsonItem(path.readBytes())
}
}
@@ -16,27 +16,30 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSon3JsonItem.Companion.getJsonItem
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJackson3Module
import com.mingliqiye.utils.json.objects.base.*
import tools.jackson.core.type.TypeReference
import tools.jackson.databind.JsonNode
import tools.jackson.databind.ObjectMapper
import tools.jackson.databind.node.JsonNodeType
import tools.jackson.databind.node.ObjectNode
import java.lang.reflect.Type
class Jackson3JsonApi : JsonApi {
var get: () -> ObjectMapper
var set: (ObjectMapper) -> Unit
var get: () -> ObjectMapper = { _prObjectMapper!! }
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
private var _prObjectMapper: ObjectMapper? = null
@@ -47,8 +50,6 @@ class Jackson3JsonApi : JsonApi {
constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper
get = { _prObjectMapper!! }
set = { _prObjectMapper = it }
}
constructor(
@@ -59,6 +60,10 @@ class Jackson3JsonApi : JsonApi {
this.set = set
}
constructor() {
_prObjectMapper = ObjectMapper()
}
override fun <T> parse(json: String, clazz: Class<T>): T {
try {
return objectMapper.readValue(json, clazz)
@@ -97,7 +102,7 @@ class Jackson3JsonApi : JsonApi {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
} catch (_: Exception) {
false
}
}
@@ -214,4 +219,80 @@ class Jackson3JsonApi : JsonApi {
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)
}
}
}
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}")
}
}
}
}
class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString())
class JackSon3JsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
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 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()
}
}
}
}
class JackSon3JsonObject(val node: JsonNode) : JsonObject() {
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 hasNext(): Boolean {
return it.hasNext()
}
}
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -27,12 +27,15 @@ import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectReader
import com.fasterxml.jackson.databind.node.JsonNodeType
import com.fasterxml.jackson.databind.node.ObjectNode
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSonJsonItem.Companion.getJsonItem
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJacksonModule
import com.mingliqiye.utils.json.objects.base.*
/**
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
@@ -97,7 +100,6 @@ class JacksonJsonApi : JsonApi {
/**
* 将对象格式化为JSON字符串
*
* @param `object` 待格式化的对象
* @return 格式化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
@@ -122,7 +124,6 @@ class JacksonJsonApi : JsonApi {
/**
* 将对象格式化为美化(带缩进)的JSON字符串
*
* @param `object` 待格式化的对象
* @return 美化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
@@ -158,7 +159,7 @@ class JacksonJsonApi : JsonApi {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
} catch (_: Exception) {
false
}
}
@@ -178,7 +179,7 @@ class JacksonJsonApi : JsonApi {
if (node.isObject) {
result.setAll<JsonNode>(node as ObjectNode)
}
} catch (e: Exception) {
} catch (_: Exception) {
}
}
return try {
@@ -293,4 +294,79 @@ class JacksonJsonApi : JsonApi {
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)
}
}
}
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}")
}
}
}
}
class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText())
class JackSonJsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
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 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()
}
}
}
}
class JackSonJsonObject(val node: JsonNode) : JsonObject() {
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 hasNext(): Boolean {
return it.hasNext()
}
}
}
}
@@ -16,20 +16,24 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-03-27 14:19:31
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.exception.JsonParserException
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import com.mingliqiye.utils.json.objects.base.JsonItem
import okio.IOException
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.readBytes
/**
* JSON处理接口,提供JSON字符串与Java对象之间的相互转换功能
@@ -46,6 +50,7 @@ interface JsonApi {
*/
inline fun <reified T> JsonApi.parse(json: String): T = parse(json, object : JsonTypeReference<T>() {})
/**
* 将JSON字节数组解析为指定泛型类型对象
*
@@ -248,6 +253,7 @@ interface JsonApi {
return parseFrom(path.toFile(), type)
}
/**
* 从文件读取JSON并解析为指定泛型类型对象
*
@@ -478,9 +484,123 @@ interface JsonApi {
*/
fun updateNodeValue(json: String, path: String, newValue: Any): String
/**
* 将任意对象转换为指定类型的对象
*
* @param source 源对象,可以是 JSON 字符串、JsonItem 或其他对象
* @param destinationClass 目标类型的 Class 对象
* @return 转换后的目标类型对象
*
* @param <D> 目标类型泛型参数
*/
fun <D> convert(source: Any, destinationClass: Class<D>): D
/**
* 将任意对象转换为指定泛型类型的对象
* 用于处理带泛型的复杂类型,如 List<User>、Map<String, User> 等
*
* @param source 源对象,可以是 JSON 字符串、JsonItem 或其他对象
* @param destinationType 目标类型的类型引用,包含泛型信息
* @return 转换后的目标类型对象
*
* @param <D> 目标类型泛型参数
*
* 使用示例:
* ```
* val typeRef = object : JsonTypeReference<List<User>>() {}
* val userList = converter.convert(jsonString, typeRef)
* ```
*/
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D
/**
* 注册自定义的 JSON 转换器
* 用于处理特定类型的自定义序列化和反序列化逻辑
*
* @param c 自定义的 JSON 转换器实例
*
* 使用示例:
* ```
* converter.addJsonConverter(DateJsonConverter())
* converter.addJsonConverter(LocalDateTimeJsonConverter())
* ```
*/
fun addJsonConverter(c: BaseJsonConverter<*, *>)
/**
* 将 JSON 字符串解析为 JsonItem 对象
*
* @param json JSON 格式的字符串
* @return 解析后的 JsonItem 对象,可以是 JsonObject、JsonArray 或 JsonValue
* @throws JsonParserException 当 JSON 格式错误时抛出
*/
fun parseJsonItem(json: String): JsonItem
/**
* 将字节数组解析为 JsonItem 对象
* 字节数组会被转换为字符串后再解析
*
* @param byte JSON 格式的字节数组(通常是 UTF-8 编码)
* @return 解析后的 JsonItem 对象
* @throws JsonParserException 当 JSON 格式错误时抛出
*/
fun parseJsonItem(byte: ByteArray): JsonItem {
return parseJsonItem(String(byte))
}
/**
* 将输入流解析为 JsonItem 对象
* 会自动关闭输入流
*
* @param inputStream JSON 数据的输入流
* @return 解析后的 JsonItem 对象
* @throws JsonParserException 当 JSON 格式错误时抛出
* @throws IOException 当读取输入流失败时抛出
*
* 使用示例:
* ```
* val inputStream = FileInputStream("data.json")
* val jsonItem = converter.parseJsonItem(inputStream)
* ```
*/
fun parseJsonItem(inputStream: InputStream): JsonItem {
inputStream.use {
return parseJsonItem(it.readAllBytes())
}
}
/**
* 将文件解析为 JsonItem 对象
*
* @param file 包含 JSON 数据的文件
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val file = File("config.json")
* val jsonItem = converter.parseJsonItem(file)
* ```
*/
@Throws(IOException::class)
fun parseJsonItem(file: File): JsonItem {
return parseJsonItem(file.readBytes())
}
/**
* 将文件路径解析为 JsonItem 对象
*
* @param path 包含 JSON 数据的文件路径
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val path = Paths.get("data/user.json")
* val jsonItem = converter.parseJsonItem(path)
* ```
*/
fun parseJsonItem(path: Path): JsonItem {
return parseJsonItem(path.readBytes())
}
}
@@ -0,0 +1,279 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonObject.kt
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.objects.base
import java.math.BigDecimal
import java.math.BigInteger
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 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 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")
}
/**
* 转换为 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
}
/** 是否为 null */
fun isNull(): Boolean = false
/** 是否为布尔值 */
fun isBoolean(): Boolean = false
/** 是否为数字 */
fun isNumber(): Boolean = false
/** 是否为字符串 */
fun isString(): Boolean = false
/** 是否为对象 */
fun isObject(): Boolean = false
/** 是否为数组 */
fun isArray(): Boolean = false
/** 返回当前元素的类型名称 */
fun name(): String = "Any"
/** 根据索引获取元素(数组专用) */
fun get(index: Int): JsonItem = getIndex(index)
/** 根据字段名获取元素(对象专用) */
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 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 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 iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
throw IllegalStateException("Current JSON element is ${name()} not a Object")
}
}
/**
* JSON 对象抽象类
* 表示键值对形式的 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()
}
/**
* JSON 数组抽象类
* 表示有序的 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()
}
/**
* JSON null 类型
* 表示 JSON 中的 null 值
*/
open class JsonNull : JsonItem {
override fun isNull(): Boolean = true
override fun name(): String = "null"
override fun toString(): String = "null"
}
/**
* JSON 数字类型
* 表示 JSON 中的数字,继承自 Number 以便转换为各种数值类型
* @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()
/** 转换为 BigDecimal */
open fun toBigDecimal(): BigDecimal = numberString.toBigDecimal()
/** 转换为指定精度的 BigDecimal */
open fun toBigDecimal(scale: Int): BigDecimal = numberString.toBigDecimal().setScale(scale)
/** 转换为 BigInteger */
open fun toBigInteger(): BigInteger = numberString.toBigInteger()
override fun toString(): String = numberString
}
/**
* JSON 字符串类型
* @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 toString(): String = value
}
/**
* JSON 布尔类型
* @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 toString(): String = value.toString()
}