How can I extract tuple array use Json4s?

535 Views Asked by At

I use Josn4s to parse json in scala, when I parse tes, will throw some exception, the code is below:

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)]

and the exception is below:

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)
1

There are 1 best solutions below

0
On

You may try this:

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