参考:
通过测试,我们发现jkad不支持map属性的json序列化,为此我们将此功能添加上去;
1. List 与 Set 考虑
因为List与Set同属于 Collection
的子类,所以,修改以下serializePropertyValue
方法:
将 serializeList
重名为 serializeCollection
,同时新增分支 serializeMap
private fun StringBuilder.serializePropertyValue(value: Any?) {
when (value) {
null -> append("null")
is String -> serializeString(value)
is Boolean, is Number -> append(value.toString())
is Collection<*> -> serializeCollection(value)
is Map<*,*> -> serializeMap(value)
else -> serializeObj(value)
}
}
2. 属性为Map的解析方法serializeMap
map 其实就是一个JsonObject,所以大括号括起来即可,新增方法如下:
对于Map中的key,json只能使用String类型的key,所以使用toString方法;
/**
* Map 实际上是一个 Object
*/
private fun StringBuilder.serializeMap(data: Map<*, *>) {
data.entries.joinToStringBuilder(this, separator = ", ", prefix = "{", postfix = "}") { it ->
serializeString(it.key.toString()) // force to String
append(":")
serializePropertyValue(it.value as Any)
}
}
2.1 测试Map类型属性
data class Person(val name: String, val age: Int) {
val map = HashMap<String, Map<String, County>>()
init {
val county1 = County("湘潭", 20)
val county2 = County("长沙", 100)
val map1 = mapOf("JavaEE" to county1, "JavaSE" to county2)
map["Java"] = map1
map["Kotlin"] = map1
}
}
class MyJsonToolsTest {
@Test
fun testMapToJson() {
val person = Person("Alice", 29)
val result = serialize(person)
println(result)
}
}
输出如下:
{
"age": 29,
"map": {
"Java": {
"JavaEE": {
"name": "湘潭",
"peopleCount": 20
},
"JavaSE": {
"name": "长沙",
"peopleCount": 100
}
},
"Kotlin": {
"JavaEE": {
"name": "湘潭",
"peopleCount": 20
},
"JavaSE": {
"name": "长沙",
"peopleCount": 100
}
}
},
"name": "Alice"
}