我有以下JSON:
[{“id_str”:“67979542”,“name”:“account”},{“id_str”:“12345678”,“name”:“account2”},{“id_str”:“3423423423”,“命名 “:” account3" }]
已被解析为带有3个元素的play.api.libs.json.JsArray对象。
我想使用以下代码将此JsArray解析为我的自定义对象Group
:
case class Group(id: String, name: String)
implicit val twitterGroupReads: Reads[Group] = (
(JsPath \\ "id_str").read[String] and
(JsPath \\ "name").read[String]
)(Group.apply _)
但我不知道如何使用该库从数组中获取所有元素并将其解析为我的自定义对象。
答案 0 :(得分:4)
Play JSON框架有a number of built-in objects用于处理JSON,其中包括Reads.traversableReads
,它将隐式用于反序列化其他类型的集合,其中可以隐式找到Reads
对象。你写了一个合适的Reads
对象。因此,除非我遗漏了某些东西,否则你很高兴:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> import play.api.libs.functional.syntax._
import play.api.libs.functional.syntax._
scala> case class Group(id: String, name: String)
defined class Group
scala> implicit val twitterGroupReads: Reads[Group] = (
| (JsPath \\ "id_str").read[String] and
| (JsPath \\ "name").read[String]
| )(Group.apply _)
twitterGroupReads: play.api.libs.json.Reads[Group] = play.api.libs.json.Reads$$anon$8@f2fae02
scala> val json = Json.parse("""[{"id_str":"67979542","name":"account"}, {"id_str":"12345678","name":"account2"}, {"id_str":"3423423423","name":"account3"}]""")
json: play.api.libs.json.JsValue = [{"id_str":"67979542","name":"account"},{"id_str":"12345678","name":"account2"},{"id_str":"3423423423","name":"account3"}]
scala> json.as[Seq[Group]]
res0: Seq[Group] = List(Group(67979542,account), Group(12345678,account2), Group(3423423423,account3))