2017-09-06 66 views
0

我用Josn4s解析斯卡拉JSON,當我分析工商業污水附加費,會拋出一些異常,代碼如下:如何提取元組數組使用Json4s?

implicit val formats = DefaultFormats 
val pos = Array[(Int, Int)]((1,3),(2,4)) 
val tes = compact(render("pos" -> Extraction.decompose(pos))) 
val dec = (parse(tes) \ "pos").extract[(Int, Int)] 

和例外下面是:

Exception in thread "main" org.json4s.package$MappingException: No usable value for _1 
Did not find value which can be converted into int 
    at org.json4s.reflect.package$.fail(package.scala:96) 
    at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:443) 
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$14.apply(Extraction.scala:463) 
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$14.apply(Extraction.scala:463) 
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) 
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) 
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) 
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) 
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) 
    at scala.collection.AbstractTraversable.map(Traversable.scala:105) 
    at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$instantiate(Extraction.scala:451) 
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(Extraction.scala:491) 
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(Extraction.scala:488) 
    at org.json4s.Extraction$.org$json4s$Extraction$$customOrElse(Extraction.scala:500) 
    at org.json4s.Extraction$ClassInstanceBuilder.result(Extraction.scala:488) 
    at org.json4s.Extraction$.extract(Extraction.scala:332) 
    at org.json4s.Extraction$.extract(Extraction.scala:42) 
    at org.json4s.ExtractableJsonAstNode.extract(ExtractableJsonAstNode.scala:21) 
+0

你正在使用哪個版本的json4s? – jiayp89

+0

@ jiayp89 json4s-jackson_2.10:3.2.10 – jinyu0310

回答

0

你可以試試這個:

import org.json4s._ 
import org.json4s.jackson.Serialization.write 
import org.json4s.jackson.JsonMethods._ 
implicit val formats = DefaultFormats 
val json = write(pos.toMap.map { case (k,v) => (k.toString -> v) }) 
val arrayTuple2 = parse(json).values.asInstanceOf[Map[Int,Int]].toArray