2017-09-19 59 views
0

我正在使用Jackson將json字符串解析爲scala案例類實例。 這裏是我的代碼遞歸類型轉換jackson json解析器

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper} 
import com.fasterxml.jackson.module.scala.DefaultScalaModule 
import scala.reflect.{ClassTag, _} 

object JsonUtil { 
    val jacksonMapper = new ObjectMapper() 
    jacksonMapper.registerModule(DefaultScalaModule) 
    jacksonMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false) 
    jacksonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 

    def toJson(value: Map[Symbol, Any]): String = { 
    toJson(value map { case (k,v) => k.name -> v}) 
    } 

    def toJson(value: Any): String = { 
    jacksonMapper.writeValueAsString(value) 
    } 

    def fromJson[T: ClassTag](json: String): T = { 
    jacksonMapper.readValue[T](json, classTag[T].runtimeClass.asInstanceOf[Class[T]]) 
    } 
} 

,這是該JSON解析錯誤

case class Person(name: String, age: Long, score: List[Long]) 
val person = JsonUtil.fromJson[Person]("""{"name": 123654,"age":23, "score": [6,7,9]}""") 
person.name 
person.score 
person.score.head 
res0: String = 123654 
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long 
    at scala.runtime.BoxesRunTime.unboxToLong(ws.sc93376:101) 
    at #worksheet#.#worksheet#(ws.sc93376:35) 

我知道傑克遜是足夠聰明的數字類型,字符串,數字,反之亦然之間進行轉換,但似乎只適用於非收集情況。

我怎麼能做得更好,力量傑克遜遞歸轉換內部集合類型?

回答