【问题标题】:play json in scala: deserializing json ignoring unknown fields在scala中播放json:反序列化json忽略未知字段
【发布时间】:2017-09-01 06:36:34
【问题描述】:

我有一个 JSON 响应,我想将其解析为案例类。但我只关心来自 JSON 的某些字段子集。例如: JSON 返回 {id: XYZ, name: ABC, ...// 更多字段 } 我只关心案例类上的字段以及我想忽略的所有其他字段(那些未映射到案例类的字段只是忽略)类似于杰克逊通过@JsonIgnoreProperties 注释为Java 所做的事情。

Scala 有类似的方法吗?

【问题讨论】:

  • 一个简单的 Reader 或 Format 已经忽略了不属于该对象的额外字段
  • @rekiem87 反过来呢?当案例类具有 JSON 中不存在的额外字段并且您希望它们被忽略时?
  • 然后您可以创建阅读器(检查下面的答案)并为其他字段分配默认值,或者将它们设为可选并将其保留为 None

标签: json scala playframework deserialization


【解决方案1】:

你只需要做阅读器,如果 Json 满足你的对象(它具有你对象的所有属性,如果有更多也没关系),那么你可以做一个简单的阅读器(或者如果你想要它的格式读和写)。示例:

case class VehicleForList(
  id: Int,
  plate: String,
  vehicleTypeName: String,
  vehicleBrandName: String,
  vehicleBrandImageUrl: Option[String],
  vehicleColorName: String,
  vehicleColorRgb: String,
  ownerName: String,
  membershipCode: Option[String],
  membershipPhone: Option[String]
)

object VehicleForList {
  implicit val vehicleForListFormat: Format[VehicleForList] = Json.format[VehicleForList]
}

如果您需要更复杂的对象来处理对象,那么您可以手动创建阅读器:

case class VehicleForEdit(
  id: Int,
  plate: String,
  ownerName: Option[String],
  membershipId: Option[Int],
  vehicleTypeId: Int,
  vehicleBrandId: Int,
  vehicleColorId: Int
)

object VehicleForEdit {
  implicit val vehicleForEditReads: Reads[VehicleForEdit] = (
    (__ \ "id").read[Int] and
    (__ \ "plate").readUpperString(plateRegex) and
    (__ \ "ownerName").readNullableTrimmedString(defaultStringMinMax) and
    (__ \ "membershipId").readNullable[Int] and //This field is optional, can be or not be present in the Json
    (__ \ "vehicleTypeId").read[Int].map(_.toString) and // Here we change the data type
    (__ \ "vehicleBrandId").read[Int] and
    (__ \ "vehicleColorId").read[Int]
  )(VehicleForEdit.apply _)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多