使用Play 2.1.1遍历JSON中的数组 [英] Iterating over an array in JSON with Play 2.1.1

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

问题描述

我正在使用播放2.1.1,并且在遍历数组时遇到问题.我在某处阅读过可以为List [Object]创建读取的内容,但是每次尝试执行此操作时,对于显示

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]]". The issue is " = 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天全站免登陆