scala - 使用json4s提取字符串值

标签 scala json4s

我有以下针对json4s的Scala控制台 session ,在这里我试图从已解析的json中提取String值:

scala> import org.json4s._
import org.json4s._

scala> import org.json4s.native.JsonMethods._
import org.json4s.native.JsonMethods._

scala> val s = """ {"a": "hello"} """
s: String = " {"a": "hello"} "

scala> val json = parse(s)
json: org.json4s.JValue = JObject(List((a,JString(hello))))

scala> json \ "a"
res0: org.json4s.JValue = JString(hello)

scala> res0.extract[String]
<console>:17: error: No org.json4s.Formats found. Try to bring an instance of org.json4s.Formats in scope or use the org.json4s.DefaultFormats.
              res0.extract[String]
                          ^

scala> import org.json4s.Formats._
import org.json4s.Formats._

scala> res0.extract[String]
<console>:20: error: No org.json4s.Formats found. Try to bring an instance of org.json4s.Formats in scope or use the org.json4s.DefaultFormats.
              res0.extract[String]
                          ^

scala> import org.json4s.DefaultFormats._
import org.json4s.DefaultFormats._

scala> res0.extract[String]
<console>:23: error: No org.json4s.Formats found. Try to bring an instance of org.json4s.Formats in scope or use the org.json4s.DefaultFormats.
              res0.extract[String]
                          ^
org.json4s.DefaultFormatsorg.json4s.Formats及其成员已经在范围内。我怎样才能解决这个问题?
EDIT1
@mfirry的答案,这可以工作:
scala> implicit val formats = DefaultFormats
formats: org.json4s.DefaultFormats.type = org.json4s.DefaultFormats$@12b195f5

scala> val json = parse(""" {"a": "hello", "b": 1.2} """)
json: org.json4s.JValue = JObject(List((a,JString(hello)), (b,JDouble(1.2))))

scala> (json \ "b").extract[String]
res6: String = 1.2

scala> (json \ "b").extract[Double]
res7: Double = 1.2

最佳答案

您只需要添加

implicit val formats = DefaultFormats

一切都会好的。

关于scala - 使用json4s提取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32378429/

相关文章:

java - java try-with-resource无法与scala一起使用

json - 反序列化没有名称的json

scala - 反序列化选项返回 None 而不是 json4s 中的异常

scala - 在json4s中提取多态类型

scala - 使用 json4s 序列化和反序列化 scala 枚举或 case 对象

scala - 具有特征的模拟类

android - Eclipse、Android、Scala 变得简单但仍然无法正常工作

json - 在 Scala 中转换 JSON 对象的问题

scala 3 内联失败一个非常简单的例子

scala - 使用 Java 反射获取 Scala trait 中的私有(private)字段