2017-08-11 29 views
0

我需要解析的JSON就像ScalaJsonCombinators如何閱讀JSON到地圖[字符串,CaseClass]

{ 
"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]] 

如何閱讀地圖[字符串,NodeTranslation]在JSON?

我沒有找到一個地圖有什麼:https://www.playframework.com/documentation/2.6.x/ScalaJsonCombinators#complex-reads

回答

1

嗯,這是多麼:

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(...) 

注:我真的很喜歡玩,JSON它並不總是易於使用,但我還沒有找到的情況下,我無法讓它做我需要的。