I'm using Jackson to parse json string to scala case class instance. Here's my code
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]])
}
}
and this's the json parsing error
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)
I know jackson is smart enough to convert between numeric types, string to numeric and vice versa, but seemingly it only works for non-collection situation.
How can I do better, that forces jackson recursively converts type inside collection?
You have to add this annotation before score: List[Long]
:
@JsonDeserialize(contentAs = classOf[java.lang.Long])
Source: https://github.com/FasterXML/jackson-module-scala/wiki/FAQ
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.