我需要解析来自JsObject的列表JsObject值。通过下面的代码,我从String获得了正常的Int和JsObject值。
我得到了什么,
def receive = {
case json_req: JsObject => {
val studentName = (json_req \ "student_name").as[String]
val studentNo = (json_req \ "student_no").as[Int]
println("studentName"+student_name)
println("studentNo"+student_no)
}
}上面的代码打印学生姓名和学生编号。
我需要什么
JSONObject
{"student_records":[
{"student_id":9,"class_id":9},
{"student_id":10,"class_id":10},
{"student_id":11,"class_id":11}
]}从上面的JsonObject中,我需要得到两个列表值,可能是学生ids列表和类ids列表。
StudentList = List[9,10,11]
ClassList = List[9,10,11]我试过什么
def receive = {
case json_req: JsObject => {
try {
val StudentList = (json_req \ "student_records" \\ "student_id").map(_.as[Int]).toList
val ClassList = (json_req \ "student_records" \\ "class_id").map(_.as[Int]).toList
println("StudentList = "+StudentList)
println("ClassList = "+ClassList)
} catch {
case e: Exception => println(e)
}
}
}我尝试过的代码给出了这个Exception
play.api.libs.json.JsResultException: JsResultException(errors:List((,List(Valid
ationError(error.expected.jsnumber,WrappedArray())))))发布于 2015-10-15 13:39:01
如果您使用问题中使用的相同的"JSONObject“字符串,那么您的代码将如您所期望的那样工作(尽管您不应该使用标题大小写,除非它是常量)。
您所看到的错误是因为您期望数字中的一个值实际上不是一个JsNumber。可能是未定义的,可能是字符串,可能是null,甚至可能是数组。如果它是一个字符串,那么它可能仍然是一个Int,您只需要正确地解析它。要使您的代码更加灵活,并更好地指示发生了什么错误,您可以做的是手动处理JsValue。如果您查看下面的jsValueToInt方法,您可以看到如何获取ht JsValue并手动将其转换为Int。
// notice that the class_id: "10" is actually a String in this version
val json_req = Json.parse(
"""
|{"student_records":[
|{"student_id":9,"class_id":9},
|{"student_id":10,"class_id":"10"},
|{"student_id":11,"class_id":11}
|]}
""".stripMargin)
def jsValueToInt(jsval: JsValue): Int = jsval match {
case JsNumber(x) => x.toInt
case JsString(s) => s.toInt // may throw a NumberFormatException
case anythingElse => throw new IllegalArgumentException(s"JsValue cannot be parsed to an Int: $anythingElse")
}
val studentList = (json_req \ "student_records" \\ "student_id").map(jsValueToInt).toList
val classList = (json_req \ "student_records" \\ "class_id").map(jsValueToInt).toListhttps://stackoverflow.com/questions/33149379
复制相似问题