【问题标题】:Extract fields from JsArray in scala on play framework在播放框架的scala中从JsArray中提取字段
【发布时间】:2014-10-08 16:46:14
【问题描述】:

我有一个来自服务器的如下 JSArray(我无法更改,因为它属于其他人):

[ {"name": "US", "id": 0, "translations" : {"name: {"es": "Estados unidos", "fr": "Etats-unis"}}},
{"name": "UK", "id": 1, "translations" : {"name: {"es": "Estados Kdda", "fr": "dsfjas"}}},
...
]

我需要提取所有名称,例如 US、UK,但不是 translations 中的名称和 id。

我尝试了几种方法,但总是有问题。以下是我尝试过的。

我第一次尝试

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

implicit object CountryReads extends Reads[Country] {  
def reads(json: JsValue) = Country(
                        (json \ "name"),
                        (json \ "id")
                    )
}

val countries = Json.parse(result) match {  //here result is Json String
           case JsArray(Seq(t)) => Some(t.as[Seq[Country]])
           case _ => None
}

但我得到如下编译错误:

[error] C:\git9\hss\app\models\LivingSocial.scala:80: type mismatch;
[error]  found   : play.api.libs.json.JsValue
[error]  required: play.api.libs.json.JsResult[MyCountry]
[error]                        def reads(json: JsValue) =    (json \ "currencyCode")
[error]                                                            ^
[error] one error found
[error] (compile:compile) Compilation failed

然后我尝试了:

val jResult = Json.parse(result)
(jResult \\ "name").foreach { name => 
   println(name.as[String])
}

我在println() 中遇到错误,因为“\”也会递归提取翻译下的名称。

有什么好的方法吗?

【问题讨论】:

  • 您的编译器错误引用了一个不在您的代码中的currencyCode 字段。你确定这就是一切吗?

标签: scala playframework playframework-2.0


【解决方案1】:

您可以将您的阅读更改为如下所示:

implicit val CountryReads: Reads[Country] = (
        (JsPath \ "name").read[String] and
          (JsPath \ "name").read[String]
        )(Country.apply _)

这是根据播放文档创建阅读器的正确方法

【讨论】:

【解决方案2】:
case class Country(name: String, id: Int, translations: Map[String, Map[String, String]])

object Country {

  implicit val format = Json.format[Country]

}

val js = Json.parse(yourString)

val names: JsResult[Seq[String]] = js.validate[Seq[Country]].map { countries => countries.map(_.name) }

此时您可以处理JsResult,因为如果 JSON 不符合您的期望,您需要进行错误处理。

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 2014-04-18
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2013-09-22
    相关资源
    最近更新 更多