我有两个Json对象通过使用Scala,我如何合并这两个?

问题描述

val jsonReq = {"name":"Scott","age":"33"}
val jsonRes = {"name":"Scott","location":"London"}

combinedJson应该是

val combinedJson = {"name":"Scott","age":"33","location":"London"}

由于我是新手,所以我在Scala中对此一无所知。

有人可以帮忙吗?

解决方法

您可以使用https://github.com/mipastgt/JFXToolsAndDemos#fxml-checker库与Json一起使用。

import org.json4s._
import org.json4s.native.JsonMethods._


val a = parse(""" {"name":"Scott","age":33} """)
val b = parse(""" {"name":"Scott","location":"London"} """)

val c = a merge b
println(c.toString)

println(c \ "name")
println(c \ "age")
println(c \ "location")


implicit val formats = DefaultFormats

val name: String = (c \ "name").extract[String]
println(s"name: $name")

val age: Int = (c \ "age").extract[Int]
println(s"age: $age")

case class Person(name: String,age: Int,location: String)
val p = c.extract[Person]
println(p)

输出将是:

JObject(List((name,JString(Scott)),(age,JInt(33)),(location,JString(London))))
JString(Scott)
JInt(33)
JString(London)
name: Scott
age: 33
Person(Scott,33,London)
,

使用Dijon库安全地解析和合并JSON对象。

  1. 在您的build.sbt中添加依赖项:
libraryDependency += "com.github.pathikrit" %% "dijon" % "0.3.0"
  1. 添加所需的导入:
import scala.language.dynamics._
import com.github.pathikrit.dijon._
  1. 解析输入的JSON值并打印合并的JSON值:
val jsonReq = parse("""{"name":"Scott","age":"33"}""")
val jsonRes = parse("""{"name":"Scott","location":"London"}""")
val jsonMerged = jsonReq ++ jsonRes
println(jsonMerged)

它将输出:

{"name":"Scott","age":"33","location":"London"}