代码之家  ›  专栏  ›  技术社区  ›  angelokh

使用Play Json和Salat格式化可为空的序列或对象列表

  •  4
  • angelokh  · 技术社区  · 11 年前

    我想将json转换为Salat模型。我正在使用Play2.X Scala Json。我找不到任何可以格式化空序列的文档。根据 https://github.com/novus/salat/wiki/SupportedTypes ,我不能使用Option[Seq]或Option[List]。

    下面的json很好,但有时会缺少“locations”。

    {
        "id": 581407,
        "locations": [
            {
                "id": 1692,
                "tag_type": "LocationTag",
                "name": "san francisco",
                "display_name": "San Francisco"
            }]
    }
    

    以下是类别:

    case class User(
     var id: Int,
     var locations: Seq[Tag] = Seq.empty
    )
    
    case class Tag(
      id: Int,
      tag_type:String,
      name:String,
      display_name:String
    )
    

    如何设置可为空的“位置”格式?

    implicit val format: Format[User] = (
        (__ \ 'id).format[Int] and
        (__ \ 'locations).formatNullable(Seq[Tag])
    )
    
    1 回复  |  直到 11 年前
        1
  •  9
  •   Travis Brown    11 年前

    Format 是不变函子,因此可以使用 inmap 更改 Option[Seq[Tag]] 将格式转换为 Seq[Tag] :

    import play.api.libs.functional.syntax._
    import play.api.libs.json._
    
    implicit val formatTag: Format[Tag] = Json.format[Tag]
    
    implicit val formatUser: Format[User] = (
      (__ \ 'id).format[Int] and
      (__ \ 'locations).formatNullable[Seq[Tag]].inmap[Seq[Tag]](
        o => o.getOrElse(Seq.empty[Tag]),
        s => if (s.isEmpty) None else Some(s)
      )
    )(User.apply, unlift(User.unapply))
    

    这不会产生 locations 值,但如果在这种情况下需要空数组,则只需更改 None 在第二个参数中 囚犯,囚犯 Some(Seq.empty) .