1

I want to get the differences between two Jsons in a readable format. The answer on this thread uses Java Maps. I tried converting ObjectNodes to Scala Maps with no success:

val objectMapper = new ObjectMapper()
val jsonNode = objectMapper.readValue(expectedJson, classOf[ObjectNode])
val otherNode = objectMapper.readTree(serviceJson).asInstanceOf[ObjectNode]
val converted = objectMapper.convertValue(jsonNode, new TypeReference[Map[String, Any]] {})

Is there a way to convert an ObjectNode into a map so that I can use, for example, the Guava function given in the other answer? Maybe there is a simpler way to compare and get the difference between two Jsons in Scala?

ArthurDocs
  • 25
  • 4

1 Answers1

1

First of all you need to register DefaultScalaModule module. You can find it on Maven repository page: Jackson Module Scala.

When you register it you can easily deserialise JSON directly to the Map. Of course, root JSON node must be a JSON Object.

For example, let's assume we have two JSON payloads:

{
  "field": "https://somethingh.com",
  "type": "object",
  "metaType": "object"
}

and

{
  "type2": "object",
  "metaType": "object2"
}

We can read it as shown below:

import com.fasterxml.jackson.databind.json.JsonMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import java.io.File
import scala.collection.immutable

object JsonScalaApp {

  def main(args: Array[String]) {
    val jsonFile = new File("./src/main/resources/test.json")
    val jsonFile2 = new File("./src/main/resources/test2.json")
    val mapper = JsonMapper.builder()
      .addModule(DefaultScalaModule)
      .build()
    val map1 = mapper.readValue(jsonFile, classOf[immutable.HashMap[String, Any]])
    val map2 = mapper.readValue(jsonFile2, classOf[immutable.HashMap[String, Any]])
    val diff1 = (map1.toSet diff map2.toSet).toMap
    val diff2 = (map2.toSet diff map1.toSet).toMap

    println(map1)
    println(map2)
    println(diff1)
    println(diff2)
  }
}

Above code prints:

Map(field -> https://somethingh.com, type -> object, metaType -> object)
Map(type2 -> object, metaType -> object2)
Map(field -> https://somethingh.com, type -> object, metaType -> object)
Map(type2 -> object, metaType -> object2)

You can use custom implementation to find all differences from linked question.

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146