使用Play框架在Scala中解析Json字符串 [英] Parsing a Json String in Scala using Play framework
问题描述
我开始尝试Scala和Play来解析Json数据,并在 https://www.playframework.com/documentation/2.3.9/ScalaJson . 现在,当我尝试运行给出的示例代码时:
I started trying Scala and Play to parse through Json data, and was following the tutorial at https://www.playframework.com/documentation/2.3.9/ScalaJson. Now, when I try to run the sample code given there which is:
val json: JsValue = Json.parse("""{
"name" : "Watership Down",
"location" : {
"lat" : 51.235685,
"long" : -1.309197
},
"residents" : [ {
"name" : "Fiver",
"age" : 4,
"role" : null
}, {
"name" : "Bigwig",
"age" : 6,
"role" : "Owsla"
} ]
}
""")
val lat = json \ "location" \ "lat"
我收到以下错误:
java.lang.NoSuchMethodError: play.api.libs.json.JsValue.$bslash(Ljava/lang/String;)Lplay/api/libs/json/JsValue;
我做错了什么?我正在使用Scala 2.10和Play 2.3.9.
What am I doing wrong? I'm using Scala 2.10 and Play 2.3.9.
谢谢.
推荐答案
在Play 2.4.x中,JsLookupResult表示特定Json路径(实际的Json节点或未定义)上的值. JsLookupResult具有两个子类:分别为JsDefined和JsUndefined.
In Play 2.4.x, JsLookupResult represents the value at a particular Json path, either an actual Json node or undefined. JsLookupResult has two subclasses: JsDefined and JsUndefined respectively.
您可以按以下方式修改代码:
You can modify your code as the following:
val name: JsLookupResult = json \ "user" \ "name"
name match {
case JsDefined(v) => println(s"name = ${v.toString}")
case undefined: JsUndefined => println(undefined.validationError)
}
这篇关于使用Play框架在Scala中解析Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!