Skip to content

Conversation

@tilumi
Copy link

@tilumi tilumi commented Aug 1, 2018

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant