玩ScalaJSON Reads[T]解析
Play ScalaJSON Reads[T] parsing
我正在编写一个 Json 解析用于休息 web 服务响应,我有一个 Json 文件看起来像:
{"program": {
"name": "myname",
"@id": "12345",
"$": "text text text"
}, etc. etc.
我为 Reads 对象写了一个案例class:
case class program(name:String)
implicit val programFormat = Json.format[program]
以及获取数据的伪代码:
val x=(jobj \ "program").validate[program]
x match {
case JsSuccess(pr, _) => println("JsSuccess:"+pr)
for(p<- pr.program)
{
println(p.name)
}
case error: JsError => ....
}
对于字段名没问题,代码运行良好,但我不明白如何捕获字段“@id”和字段“$”,因为我无法创建参数以防万一class命名:@id 或 $.
感谢您的帮助。
我认为更正确的解决方案是创建自己的 Reads
,即:
case class Program(name: String, id: String, dollar: String)
implicit val programWrites: Reads[Program] = (
(__ \ "name").read[String] ~
(__ \ "@id").read[String] ~
(__ \ "$").read[String]
)(Program.apply _)
文档:https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Reads
另一个我认为更糟糕的解决方案是使用反引号
case class Program(name: String, `@id`: String, `$`: String)
implicit val programFormat = Json.format[Program]
允许在方法名、字段名等处写特殊符号。
更多相关信息:Need clarification on Scala literal identifiers (backticks)
我正在编写一个 Json 解析用于休息 web 服务响应,我有一个 Json 文件看起来像:
{"program": {
"name": "myname",
"@id": "12345",
"$": "text text text"
}, etc. etc.
我为 Reads 对象写了一个案例class:
case class program(name:String)
implicit val programFormat = Json.format[program]
以及获取数据的伪代码:
val x=(jobj \ "program").validate[program]
x match {
case JsSuccess(pr, _) => println("JsSuccess:"+pr)
for(p<- pr.program)
{
println(p.name)
}
case error: JsError => ....
}
对于字段名没问题,代码运行良好,但我不明白如何捕获字段“@id”和字段“$”,因为我无法创建参数以防万一class命名:@id 或 $.
感谢您的帮助。
我认为更正确的解决方案是创建自己的 Reads
,即:
case class Program(name: String, id: String, dollar: String)
implicit val programWrites: Reads[Program] = (
(__ \ "name").read[String] ~
(__ \ "@id").read[String] ~
(__ \ "$").read[String]
)(Program.apply _)
文档:https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Reads
另一个我认为更糟糕的解决方案是使用反引号
case class Program(name: String, `@id`: String, `$`: String)
implicit val programFormat = Json.format[Program]
允许在方法名、字段名等处写特殊符号。 更多相关信息:Need clarification on Scala literal identifiers (backticks)