我正在尝试使用json4s将json字符串解析为对象,但即使在运行此代码后,我也会将其作为打印结果。
JObject(List((numbers,JArray(List(JInt(1),JInt(2),JInt(3),JInt(4))))))
def main(args: Array[String]): Unit = {
val json = """{"users": [
{"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
{"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}]
}"""
val obj = parse(json).extract[List[User]]
println(obj)
}
case class User(name: String, emails: List[String])
case class UserList(users: List[User]) {
override def toString(): String = {
this.users.foldLeft("")((a, b) => a + b.toString)
}
}
请帮忙
答案 0 :(得分:3)
只需添加implicit val formats = DefaultFormats
并将genric类型更改为UserList
:
import org.json4s._
import org.json4s.native.JsonMethods._
object Test {
def main(args: Array[String]): Unit = {
implicit val formats = DefaultFormats
val json = """{"users": [
{"name": "Foo", "emails": ["Foo@gmail.com", "foo2@gmail.com"]},
{"name": "Bar", "emails": ["Bar@gmail.com", "bar@gmail.com"]}]
}"""
val obj = parse(json).extract[UserList]
println(obj)
}
}
case class User(name: String, emails: List[String])
case class UserList(users: List[User])
,输出为:
UserList(列表(用户(Foo,列表(Foo@gmail.com,foo2@gmail.com)),用户(栏,列表(Bar@gmail.com,bar @ gmail.com))))