scala – 使用json4s提取字符串值
发布时间:2020-12-16 09:23:30 所属栏目:安全 来源:网络整理
导读:我有以下Scala控制台会话为json4s,我试图从解析的json中提取字符串值: 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
我有以下Scala控制台会话为json4s,我试图从解析的json中提取字符串值:
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.DefaultFormats,org.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 它会正常工作. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |