Last active
March 1, 2017 22:58
-
-
Save choffmeister/3e68465507bb99815bf61daabc1363f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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