使用 Play 2.1.1 在 JSON 中迭代数组 [英] Iterating over an array in JSON with Play 2.1.1

查看:22
本文介绍了使用 Play 2.1.1 在 JSON 中迭代数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 play 2.1.1,但在遍历数组时遇到问题.我曾在某处读到您可以为 List[Object] 创建一个读取,但是每次我尝试这样做时,我都会收到一个错误 "No unapply function found" 对于说

I am using play 2.1.1 and I am having issues iterating through an array. I had read somewhere that you can create a reads for a List[Object] but everytime I try to do this I get an error "No unapply function found" for the line that says

implicit val userListReads: Reads[List[FBUser]] = Json.reads[List[FBUser]]".问题是"= Json.reads[List[FBUser]]

我不知道还有什么可以尝试的.任何帮助将不胜感激.

I am at a loss of what else to try. Any assistance would be greatly appreciated.

def linkUsers() = Action { implicit request =>
  val json = Json.parse("{"data": [{"name": "Me Lazyan","id": "1182"},{"name": "Chales Dselle","id": "10115"},{"name": "Be My","id": "10275"},{"name": "De Rwani", "id": "11189"},{"name": "Phoe Johon", "id": "11372"}]}")

  val peoples = json.validate[List[FBUser]].get
  peoples.foreach(println)

  Ok(json).withHeaders(CONTENT_TYPE -> "text/json")
}

case class FBUser(
  name: String,
  id: String 
)

object FBUser {
    /** Uses a Scala Macro to define the Reads function */
    implicit val userReads: Reads[FBUser] = Json.reads[FBUser]
    implicit val userListReads: Reads[List[FBUser]] = Json.reads[List[FBUser]]
}

推荐答案

您的 json 值是一个对象,其字段 data 包含一个数组.您正在尝试将单个对象解析为数组.您要么必须将 json 更改为.

Your json value is an object with field data containing an array. You are trying to parse the single object as an array. You would either have to change json to.

val json = Json.parse("[{"name": "Me Lazyan","id": "1182"},{"name": "Chales Dselle","id": "10115"},{"name": "Be My","id": "10275"},{"name": "De Rwani", "id": "11189"},{"name": "Phoe Johon", "id": "11372"}]")

或将您的代码更改为

val people = (json  "data").validate[List[FBUser]].get

这篇关于使用 Play 2.1.1 在 JSON 中迭代数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆