簡體   English   中英

ScalaJsonCombinators如何將JSON讀取到Map [String,CaseClass]

[英]ScalaJsonCombinators how to read JSON to Map[String, CaseClass]

我需要解析的JSON就像

{
"state": "active",
"id": "11775",
"translations": {
  "de_CH": {
    "name": "Spiegel",
    "url": "spiegel-sale"
  },
  "fr_CH": {
    "name": "Miroirs",
    "url": "promo-miroirs-femme"
  }
 }

在翻譯中,鍵de_CHfr_CH事先未知。 其他鍵是已知的。

對我而言,翻譯對象可以像字典一樣建模。

這是案例類

case class Category(
  id: String,
  order: Int,
  translations: Map[String, NodeTranslation]
)

case class NodeTranslation(name: String, url: String)

ScalaJsonCombinators讀取的是

implicit val categoryReads = Json.format[Category
implicit val nodeTranslationReads = Json.format[NodeTranslation]]

如何在JSON中讀取Map [String,NodeTranslation]?

我在那里找不到任何地圖: https : //www.playframework.com/documentation/2.6.x/ScalaJsonCombinators#complex-reads

嗯,這就是方法:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Category(
  id: String,
  order: Int,
  translations: Map[String, NodeTranslation]
)
case class NodeTranslation(name: String, url: String)

implicit val nodeTranslationReads = Json.format[NodeTranslation]
implicit val categoryReads: Reads[Category] = (
  (__ \ 'id).read[String] and
  Reads.pure[Int](123) and // your example json doesn't contain an order member so I'm not sure what you expect here
  (__ \ 'translations).read[JsObject].map { obj =>
    obj.value.mapValues(_.as[NodeTranslation]).toMap
  }
)(Category.apply(_, _, _))

現在在repl中對其進行測試:

val js =
  """
    |{
    |"state": "active",
    |"id": "11775",
    |"translations": {
    |  "de_CH": {
    |    "name": "Spiegel",
    |    "url": "spiegel-sale"
    |  },
    |  "fr_CH": {
    |    "name": "Miroirs",
    |    "url": "promo-miroirs-femme"
    |  }
    | }
    |}
  """.stripMargin
val json = Json.parse(js)

json.as[Category]

結果是:

Category(11775,123,Map(de_CH -> NodeTranslation(Spiegel,spiegel-sale), fr_CH -> NodeTranslation(Miroirs,promo-miroirs-femme)))

請注意,如果要為Category創建格式化程序,則必須使用:

(__ \ 'translations).format[JsObject].inmap(...)

nb:我真的很喜歡play-json,它並不總是很容易使用,但是我還沒有找到一種情況,我無法讓它做我需要的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM