合并额外的属性到第二级JSON字符串



我有一个Json字符串,如:

{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test"
}
}

我想合并2多个字段到level 2块(不是根级)。它们是:

timeout = 5000
waityes = false
所以输出的JSON将是:
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test",
"timeout": 5000,
"waityes": "false"
}
}

我用这两个字段创建了一个Kotlin数据类(不确定这是否正确??)

data class PropertiesToAdd(val timeout: Int = 5000, val waityes: String = "false")

但是我不确定如何将kotlin数据类与初始JSON字符串合并。我先转换PropertiesToAdd到JSON然后以某种方式组合它们吗??

我不想为初始JSON对象创建模型类(这篇文章中的第一个例子)。(见下文)

{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test"
}
}

我知道我可以使用JSON对象合并两个JSON,但不确定如何添加到一个二级元素,如level 2对象在上面的例子。

不需要模型类就可以工作:

val startJson = """
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test"
}
}"""
val endJson = JSONObject(startJson)
endJson.getJSONObject("level 2").put("timeout",5000).put("waityes","false")

endJson.toString()将是您期望的输出,如下所示:

{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test",
"timeout": 5000,
"waityes": "false"
}
}

最新更新