简体   繁体   中英

play json in scala: deserializing json ignoring unknown fields

I have a JSON response which I want to parse to a case class. But I only care about certain subset of fields coming from the JSON. For example: JSON returns {id: XYZ, name: ABC, ...// more fields } I only care about the fields that are on the case class and all the rest I want to ignore (those fields which aren't mapped to the case class just ignore) similar to how Jackson does it for Java via @JsonIgnoreProperties annotation.

Is there a similar approach for Scala?

You only have to do the reader, if the Json fulfill your object (It has all the properties of your object, does not matter if have more), then you can do a simple reader (or Format if you want it to read and write). Example:

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]
}

If you need something more complex for you object then you can make the reader manually:

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 _)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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