我不知道如何使用json4s序列化具有选项值的元组列表,因此它可以再次反序列化它。以下示例显示了(de)序列化的类型:
import org.json4s.jackson.Serialization.{read, write}
implicit val formats = DefaultFormats
case class ListTupleOptionValue(l: List[(String, Option[String])])
// Everything is fine having a defined value
val withSomeValueJson = write(ListTupleOptionValue(List(("bKey", Some("bValue")))))
read[ListTupleOptionValue](withSomeValueJson)
// Serialization is faulty or at least deserialization cannot handle it
val withNoneValue = ListTupleOptionValue(List(("bKey", None)))
val withNoneValueJson = write(withNoneValue)// {"l":[{}]} notice the {} empty object definition in the list []
// this works when not having the {} empty object definition
read[ListTupleOptionValue]("{\"l\":[]}")
// this fails with "No usable value for l"
read[ListTupleOptionValue](withNoneValueJson)
尝试时的输出是
No usable value for l
Expected object with 1 element but got JObject(List())
org.json4s.package$MappingException: No usable value for l
Expected object with 1 element but got JObject(List())
at org.json4s.reflect.package$.fail(package.scala:95)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(Extraction.scala:521)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$14.apply(Extraction.scala:541)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$14.apply(Extraction.scala:541)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at org.json4s.Extraction$ClassInstanceBuilder.instantiate(Extraction.scala:529)
at org.json4s.Extraction$ClassInstanceBuilder.result(Extraction.scala:592)
at org.json4s.Extraction$.extract(Extraction.scala:387)
at org.json4s.Extraction$.extract(Extraction.scala:39)
at org.json4s.ExtractableJsonAstNode.extract(ExtractableJsonAstNode.scala:21)
at org.json4s.jackson.Serialization$.read(Serialization.scala:50)
at org.json4s.Serialization$class.read(Serialization.scala:30)
at org.json4s.jackson.Serialization$.read(Serialization.scala:17)
有关如何使此代码示例工作的任何建议? 提前谢谢。
最好的问候Trym