Skip to content

Instantly share code, notes, and snippets.

@choffmeister
Last active March 1, 2017 22:58
Show Gist options
  • Save choffmeister/3e68465507bb99815bf61daabc1363f9 to your computer and use it in GitHub Desktop.
Save choffmeister/3e68465507bb99815bf61daabc1363f9 to your computer and use it in GitHub Desktop.
package demo
import java.time.Instant
import java.util.UUID
import demo.RootJsonFormatWithDefault.toRootJsonFormatWithDefault
import spray.json._
final case class User(id: String, name: String, timestamp: Long)
trait JsonProtocol extends DefaultJsonProtocol {
// use default json format for user and extend this with two default values
implicit val userFormat = jsonFormat3(User)
.withDefault("_id", "some-random-id")
.withDefault("timestamp", System.currentTimeMillis)
}
package demo
import spray.json._
import scala.language.implicitConversions
class RootJsonFormatWithDefault[T](inner: RootJsonFormat[T]) {
def withDefault[V](key: String, defaultValue: => V)(implicit writer: JsonWriter[V]): RootJsonFormat[T] = new RootJsonFormat[T] {
override def read(json: JsValue) = {
if (json.asJsObject.fields.contains(key)) inner.read(json)
else inner.read(JsObject(json.asJsObject.fields + (key -> writer.write(defaultValue))))
}
override def write(obj: T) = inner.write(obj)
}
}
object RootJsonFormatWithDefault {
implicit def toRootJsonFormatWithDefault[T](inner: RootJsonFormat[T]): RootJsonFormatWithDefault[T]
= new RootJsonFormatWithDefault(inner)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment