spray / spray-json

A lightweight, clean and simple JSON implementation in Scala
Apache License 2.0
972 stars 190 forks source link

check num of fields in JSON match num of fields in case class #271

Open tilumi opened 6 years ago

tilumi commented 6 years ago

Following test will failed since the case class accidentally parsed to a different case class, so I think check number of fields is necessary.

trait Entity
case class Alert(name: String) extends Entity
case class PerfCounterAlert(name: String, expression: String) extends Entity

implicit val perfCounterAlertFormat = jsonFormat2(PerfCounterAlert)
implicit val alertFormat = jsonFormat1(Alert)
implicit val entityFormat = jsonFormat[Entity](
      new JsonReader[Entity]{
        override def read(json: JsValue): Entity = Try(alertFormat.read(json)).getOrElse(perfCounterAlertFormat.read(json))
      }, new JsonWriter[Entity]{
        override def write(obj: Entity): JsValue = obj match {
          case entity: Alert => alertFormat.write(entity)
          case entity: PerfCounterAlert => perfCounterAlertFormat.write(entity)
        }
      }
    )

val perfCounterAlert = PerfCounterAlert("counter1", "value > 0")
val json = perfCounterAlert.toJson.prettyPrint
val entity = json.parseJson.convertTo[Entity]
println(entity)
// shows Alert("counter1")
assert(entity == perfCounterAlert)