bizzabo / play-json-extensions

+22 field case class formatter and more for play-json
http://cvogt.org/play-json-extensions/api/
Other
196 stars 44 forks source link

formatSealed problematic with schema evolution #23

Open cvogt opened 8 years ago

cvogt commented 8 years ago

if writers are running a newer version of a schema than readers, and writers add additional cases to a sealed structure,then readers can fail because of unexpected cases. Here is a pattern to solve this, which could be encoded as a another formatX method. This is for basically enums and would need to be changed

sealed abstract class All
sealed abstract class Known
object All {
  final case class Unknown( value: JsValue ) extends All
  case object Case1 extends Known
  case object Case2 extends Known
  import org.cvogt.play.json.SingletonEncoder.simpleNameUpperCase
  import org.cvogt.play.json.implicits.formatSingleton
  implicit def jsonFormat: Format[All] = new Format[All] {
    private val formatKnown = Jsonx.formatSealed[Known]
    def reads( json: JsValue ): JsResult[All] =
      formatKnown.reads( json ) orElse JsSuccess( Unknown(json) )
    def writes( o: All ): JsValue = o match {
      case Unknown(json)               => json
      case known: Known => formatKnown.writes( known )
    }
  }
}