Skip to content
Advertisement

How to merge two jsonNodes in one

I have two variables of class User as follows:

   val user1 = User().apply {....values here}
   val user2 = User().apply {....values here}

I want to create a JsonNode with the following structure:

   var node:JsonNode? = null
   node = {
    "user_1": {
       ...the fields of class User, assigned in variable user1
      },
    "user_2": {
     ...the values for user 2
    }
   }

I have converted the objects to nodes, but I do not know how to merge them using Jackson.

  val mapper1= ObjectMapper()
  mapper1.valueToTree<JsonNode>(user1)
  val mapper2= ObjectMapper()
  mapper2.valueToTree<JsonNode>(user2)

Or is there a more efficient way to create one json node structure with the two classes ? I am using Kotlin and Jackson databank.

Advertisement

Answer

I haven’t tested it, but I guess you should be able to simply create a Map<String, User> and convert that into a JsonNode:

val user1 = User().apply {....values here}
val user2 = User().apply {....values here}

val both = mapOf("user1" to user1, "user2" to user2)

val mapper = ObjectMapper()
val result = mapper.valueToTree<JsonNode>(both)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement