有一个http响应,它是一个JSON字符串
{"id":"12345","dob":"01\/01\/1991","first_name":"Joe","gender":"male"}
哪些需要实例化到此类中
case class UserRow(id: Long, firstName: String, lastName: String, dob: Long, gender: String)
我尝试将JSON解析为地图
val result = parseFull(response)
println(result)
输出
Some(Map(dob -> 01/01/1991, id -> 12345, first_name -> Joe, gender -> male))
试图得到
map.get("id").toString().toLong //Throws a NumberFormatException
Dob应该转换为Long类型的毫厘(EPOC)。感谢帮助
基本答案您可以使用https://github.com/json4s/json4s或其他JSON-lib。并使用序列化器。
我需要调整JSON和case类的某些部分。
为了处理dob字段中的时间,您可以尝试以下扩展:
// Joda Time隐式val格式= org.json4s.DefaultFormats ++ org.json4s.ext.JodaTimeSerializers.all
一些代码示例
import org.json4s._
import org.json4s.native.Serialization
implicit val formats = Serialization.formats(NoTypeHints)
val jsonExample = """{"id":12345,"firstName":"Joe","gender":"male"}"""
case class UserRow(id: Long, firstName: String, lastName: Option[String], dob: Option[Long], gender: String)
使用范例
scala> Serialization.read[UserRow](jsonExample)
res5: UserRow = UserRow(12345,Joe,None,None,male)
扩展答案
提供的JSON会导致一些问题,这些问题只能使用手工制作的反序列化器https://github.com/json4s/json4s#serialization来解决
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句