在scala中播放json:反序列化json忽略未知字段

时间:2017-08-31 21:03:55

标签: json scala playframework deserialization

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

Scala是否有类似的方法?

1 个答案:

答案 0 :(得分:1)

你只需要做读者,如果Json完成你的对象(它具有你对象的所有属性,如果有更多的话没关系),那么你可以做一个简单的阅读器(如果你想要它可以做一个Format)读和写)。例如:

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 _)
}
相关问题