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: