Issue
I have a Json string like:
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test"
}
}
I want to merge 2 more fields into the level 2 block (not root level). these are the following:
timeout = 5000
waityes = false
So the output JSON will be:
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test",
"timeout": 5000,
"waityes": "false"
}
}
I created a Kotlin data class with these 2 fields (not sure if this is the right thing to do??)
data class PropertiesToAdd(val timeout: Int = 5000, val waityes: String = "false")
But I am not sure how to merge the kotlin data class with the initial JSON string. Do I convert PropertiesToAdd to JSON first then somehow combine them??
I dont want to create model classes for the initial JSON object (the first example in this post).. (see again below)
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test"
}
}
I know I can use JSON object to merge two JSON but not sure how to add to a SECOND LEVEL element like level 2 object in the example above.
Solution
The following should work without the need for model classes:
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() will be your desired output as follows:
{
"level 1": "hello",
"level 2" : {
"test1": 0,
"test2": 5,
"test3": "this is test",
"timeout": 5000,
"waityes": "false"
}
}
Answered By - Jofbr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.