我有两个 Json 对象。通过使用 Scala,我如何合并这两者?
I have two Json Objects. By using Scala how can i merge these two?
val jsonReq = {"name":"Scott", "age":"33"}
val jsonRes = {"name":"Scott", "location":"London"}
和combinedJson
应该是
val combinedJson = {"name":"Scott", "age":"33", "location":"London"}
我在 Scala 中对此一无所知,因为我是新手。
有人可以帮忙吗?
您可以使用 json4s 库来处理 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 个对象。
- 在你的
build.sbt
中添加依赖:
libraryDependency += "com.github.pathikrit" %% "dijon" % "0.3.0"
- 添加所需的导入:
import scala.language.dynamics._
import com.github.pathikrit.dijon._
- 解析输入 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"}
val jsonReq = {"name":"Scott", "age":"33"}
val jsonRes = {"name":"Scott", "location":"London"}
和combinedJson
应该是
val combinedJson = {"name":"Scott", "age":"33", "location":"London"}
我在 Scala 中对此一无所知,因为我是新手。
有人可以帮忙吗?
您可以使用 json4s 库来处理 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 个对象。
- 在你的
build.sbt
中添加依赖:
libraryDependency += "com.github.pathikrit" %% "dijon" % "0.3.0"
- 添加所需的导入:
import scala.language.dynamics._
import com.github.pathikrit.dijon._
- 解析输入 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"}