2015-09-03 10 views
22

kullanarak değeri:Özü Dize ben bir çözümlü json gelen dize değerini ayıklamak için çalışıyorum json4s için Scala konsol oturumuna şu var json4s

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 ve orada üyeleri kapsamında zaten. Bunu nasıl düzeltebilirim?

Edit1

@mfirry 'ın cevabı itibaren bu işleri:

scala> implicit val formats = DefaultFormats 
formats: org.json4s.DefaultFormats.type = [email protected] 

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 
+0

'extractOpt', alan isteğe bağlı bir ise, belirtilen türde Seçenek döndürür. – ruhong

cevap

46

sadece

implicit val formats = DefaultFormats 

eklemem gerekiyor ve sadece Tamam çalışacağız.

+10

neden bu gereklidir? – Nilesh

+0

Ve bir sınıfa ihtiyacınız varsa, bunu sadece sınıfın en üst köşesinde ilan edebilirsiniz. – cph2117

+0

Sadece bir işlevde ihtiyacınız varsa bile, yukarıdakilerden daha iyi bir şekilde bildirin. Daha fazla java.io.NotSerializableException – ivankeller