Skip to content

Commit

Permalink
fix: mergeJSON
Browse files Browse the repository at this point in the history
  • Loading branch information
arm64v8a committed Dec 11, 2024
1 parent a65f56f commit ad61b2e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,10 @@ fun buildConfig(

// custom JSON merge
if (bean.customOutboundJson.isNotBlank()) {
Util.mergeJSON(bean.customOutboundJson, currentOutbound)
Util.mergeJSON(
bean.customOutboundJson,
currentOutbound as MutableMap<String, Any?>
)
}
}

Expand Down
41 changes: 27 additions & 14 deletions app/src/main/java/moe/matsuri/nb4a/utils/Util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -113,33 +113,46 @@ object Util {
}
}

fun map2StringMap(m: Map<*, *>): MutableMap<String, Any?> {
val o = mutableMapOf<String, Any?>()
m.forEach {
if (it.key is String) {
o[it.key as String] = it.value as Any
}
}
return o
}

fun mergeJSON(j: String, to: MutableMap<String, Any>) {
if (j.isBlank()) return
val m = JavaUtil.gson.fromJson(j, to.javaClass)
m.forEach { (k, v) ->
if (v is Map<*, *> && to[k] is Map<*, *>) {
val currentMap = (to[k] as Map<*, *>).toMutableMap()
currentMap += v
to[k] = currentMap
fun mergeMap(dst: MutableMap<String, Any?>, src: Map<String, Any?>): MutableMap<String, Any?> {
src.forEach { (k, v) ->
if (v is Map<*, *> && dst[k] is Map<*, *>) {
val currentMap = (dst[k] as Map<*, *>).toMutableMap()
dst[k] = mergeMap(map2StringMap(currentMap), map2StringMap(v))
} else if (v is List<*>) {
if (k.startsWith("+")) { // prepend
val dstKey = k.removePrefix("+")
var currentList = (to[dstKey] as List<*>).toMutableList()
var currentList = (dst[dstKey] as List<*>).toMutableList()
currentList = (v + currentList).toMutableList()
to[dstKey] = currentList
dst[dstKey] = currentList
} else if (k.endsWith("+")) { // append
val dstKey = k.removeSuffix("+")
var currentList = (to[dstKey] as List<*>).toMutableList()
var currentList = (dst[dstKey] as List<*>).toMutableList()
currentList = (currentList + v).toMutableList()
to[dstKey] = currentList
dst[dstKey] = currentList
} else {
to[k] = v
dst[k] = v
}
} else {
to[k] = v
dst[k] = v
}
}
return dst
}

fun mergeJSON(j: String, dst: MutableMap<String, Any?>) {
if (j.isBlank()) return
val src = JavaUtil.gson.fromJson(j, dst.javaClass)
mergeMap(dst, src)
}

// Format Time
Expand Down

0 comments on commit ad61b2e

Please # to comment.