2017-02-17 56 views
0

我需要序列化,然後反序列化案例類對象與字段"name"從JSON,它有"animalname"字段而不是"name"。序列化工作正常,但反序列化沒有。我用FieldSerializer與renameTo()renameFrom()json4s:無法解析JSON與重命名字段

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

其實,提取物()拋出異常:

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:我用這個Maven的依賴於json4s:

<dependency> 
    <groupId>org.json4s</groupId> 
    <artifactId>json4s-jackson_2.10</artifactId> 
    <version>3.2.5</version> 
</dependency> 

回答

1

嘗試val dog = read[WildDog](json)代替val dog = parse(json).extract[WildDog]

GitHub的頁面 - https://github.com/json4s/json4s有其他一些很好的例子太多。

編輯:

工作版本:
的Scala 2.10 & & org.json4s.jackson> = 3.5.0
的Scala 2.11 & & org.json4s.jackson> = 3.2.5

我還沒有檢查早期版本的Scala 2.10,但是當我使用3.2.5時存在異常。

另外,我能得到val dog = parse(json).extract[WildDog]工作,但你必須導入JsonMethods - >import org.json4s.jackson.JsonMethods.parse

+0

試過,同樣MappingException :( –

+1

版本您正在使用什麼斯卡拉我能得到它一起工作? 2.11而不是2.10 – pjames

+0

我使用Scala 2.10,json4s 3.2.5。我想,我現在不會有機會切換到2.11 ... –