如何解决我有两个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对象。
- 在您的
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"}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。