Scala播放地图的Json格式[Locale,String]

时间:2015-12-04 10:03:27

标签: json scala playframework play-json

我有

类型的对象
Map[java.util.Locale, String] 

如何为此制作Json Writen / Reads?我查看过couple other questions,但我自己无法提出解决方案。我得到了(但尚未测试)Locale的内容

implicit val localeReads: Reads[Locale] = new Reads[Locale] {
  def reads(json: JsValue): JsResult[Locale] =
    json match {
      case JsString(langString) => JsSuccess(new Locale(langString))
      case _ => JsError("Locale Language String Expected")
    }
}

implicit val localeWrites: Writes[Locale] = new Writes[Locale] {
  def writes(locale: Locale) = JsString(locale.toString)
}

我怎样才能在

中使用它
implicit val myMapReads: Reads[Map[Locale, String]] = ???
implicit val myMapWrites: Writes[Map[Locale, String]] = ???

2 个答案:

答案 0 :(得分:0)

这应该有效:

implicit val localeReads: Reads[Locale] = new Reads[Locale] {
  def reads(json: JsValue): JsResult[Locale] =
    json match {
      case JsString(langString) => JsSuccess(new Locale(langString))
      case _ => JsError("Locale Language String Expected")
    }
}

implicit val localeWrites: Writes[Locale] = new Writes[Locale] {
  def writes(locale: Locale) = JsString(locale.toString)
}

implicit val myMapWrites: Writes[Map[Locale, String]] = new Writes[Map[Locale, String]] {
  override def writes(o: Map[Locale, String]): JsValue = Json.toJson(o)
}

implicit val myMapRead: Reads[Map[Locale, String]] = new Reads[Map[Locale, String]] {
  override def reads(json: JsValue): JsResult[Map[Locale, String]] = JsSuccess {
    json.as[JsObject].value.map {
      case (k, v) => (new Locale(k), v.as[String])
    }.toMap
  }
}

基本上游戏已经知道如何将Locale转换为json,因为您提供了Writes,因此只需调用toJson即可。

对于Reads它有点复杂并且您必须进行映射,.value会返回Map[String, JsValue],其中第一个代表Locale对象,第二个是一个简单的字符串,所以调用as[String]已经可以给你你想要的东西了。

请注意,我已将所有内容都包裹在JsSuccess中,但您可能认为您获得的json无法转换为JsObject,请尝试使用try / catch,并决定是否要使用返回成功或失败。

答案 1 :(得分:0)

如果Format[K,V]序列化为K,则此函数会为您创建JsString

/** Play Json only supports Map[String,V]. This function creates a format for Map[K,V]. The type K should produce a JsString.
 * Otherwise the serialisation will fail. Which should be good enough since in valid json keys can only be strings. 
*/
def mapFormat[K, V](implicit fk: Format[K], fv: Format[V]): Format[Map[K, V]] = 
  new OFormat[Map[K, V]] {
    override def writes(o: Map[K, V]): JsObject = {
      val stringMap = o.map { case (k, v) => (Json.toJson[K](k).as[JsString].value, v) }
      Json.toJson(stringMap).as[JsObject]
    }

    override def reads(json: JsValue): JsResult[Map[K, V]] = {
      for {
        stringMap <- Json.fromJson[Map[String, V]](json)
        _         <- Json.fromJson[Set[K]](Json.toJson(stringMap.keySet))
      } yield stringMap.map { case (k, v) => (Json.fromJson[K](JsString(k)).get, v) }
    }
  }