简体   繁体   English

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

[英]Format nullable Seq or List of objects with Play Json and Salat

I want to convert a json to Salat model. 我想将json转换为Salat模型。 I am using Play 2.X Scala Json. 我正在使用Play 2.X Scala Json。 I couldn't find any documentations to format nullable Seq. 我找不到任何格式化可空的Seq的文档。 According to https://github.com/novus/salat/wiki/SupportedTypes , I can't use Option[Seq] Or Option[List]. 根据https://github.com/novus/salat/wiki/SupportedTypes ,我不能使用Option [Seq]或Option [List]。

The following json is good, but sometimes 'locations' can be missing. 以下json是好的,但有时“位置”可能会丢失。

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

These are the classes: 这些是类:

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
)

How can I format nullable 'locations'? 如何格式化可空的“位置”?

implicit val format: Format[User] = (
    (__ \ 'id).format[Int] and
    (__ \ 'locations).formatNullable(Seq[Tag])
)

Format is an invariant functor, so you can use inmap to change a Option[Seq[Tag]] format into a format for Seq[Tag] : 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))

This will not produce a locations value when serializing a user with no locations, but if you want an empty array in that case you can just change the None in the second argument to inmap to Some(Seq.empty) . 在序列化没有位置的用户时,这不会产生locations值,但如果你想在这种情况下使用空数组,你只需将第二个参数中的None更改为inmap to Some(Seq.empty)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM