我需要使用来自JSON的字段"name"
序列化然后反序列化案例类对象,该字段具有"animalname"
字段而不是"name"
。序列化工作正常,但不反序列化。我将FieldSerializer与renameTo()
和renameFrom()
:
import org.json4s._
import org.json4s.FieldSerializer._
import org.json4s.jackson.Serialization._
case class WildDog(name: String)
val dogSerializer = FieldSerializer[WildDog](
renameTo("name", "animalname"),
renameFrom("animalname", "name"))
implicit val formats = DefaultFormats + dogSerializer
// serialize
val json = write(WildDog("beefy")) // {"animalname":"beefy"}, as expected
// try to deserialize
val dog = parse(json).extract[WildDog] // expected: Dog("beefy")
实际上,extract()抛出异常:
org.json4s.package$MappingException: No usable value for name
Did not find value which can be converted into java.lang.String
at org.json4s.reflect.package$.fail(ws.sc:94)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$buildCtorArg(ws.sc:409)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$11.apply(ws.sc:417)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$11.apply(ws.sc:417)
at scala.collection.TraversableLike$$anonfun$map$1.apply(ws.sc:240)
at scala.collection.TraversableLike$$anonfun$map$1.apply(ws.sc:240)
at scala.collection.mutable.ResizableArray$class.foreach(ws.sc:55)
at scala.collection.mutable.ArrayBuffer.foreach(ws.sc:43)
at scala.collection.TraversableLike$class.map(ws.sc:240)
at scala.collection.AbstractTraversable.map(ws.sc:101)
at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$instantiate(ws.sc:417)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(ws.sc:445)
at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(ws.sc:442)
at org.json4s.Extraction$.org$json4s$Extraction$$customOrElse(ws.sc:454)
at org.json4s.Extraction$ClassInstanceBuilder.result(ws.sc:442)
at org.json4s.Extraction$.extract(ws.sc:304)
at org.json4s.Extraction$.extract(ws.sc:38)
at org.json4s.ExtractableJsonAstNode.extract(ws.sc:17)
如何正确反序列化此JSON?
更新:我使用Scala 2.10,json4s 3.2.5。
更新2:我对json4s使用这个Maven依赖:
<dependency>
<groupId>org.json4s</groupId>
<artifactId>json4s-jackson_2.10</artifactId>
<version>3.2.5</version>
</dependency>
答案 0 :(得分:1)
尝试val dog = read[WildDog](json)
而不是val dog = parse(json).extract[WildDog]
github页面 - https://github.com/json4s/json4s也有其他一些很好的例子。
编辑:
工作版本:
Scala 2.10&amp;&amp; org.json4s.jackson&gt; = 3.5.0
Scala 2.11&amp;&amp; org.json4s.jackson&gt; = 3.2.5
我没有检查Scala 2.10的早期版本,但是当我使用3.2.5时存在异常。
此外,我可以让val dog = parse(json).extract[WildDog]
工作,但您必须导入JsonMethods
- &gt; import org.json4s.jackson.JsonMethods.parse