Skip to content

Instantly share code, notes, and snippets.

@mathieuancelin
Created January 17, 2017 07:56
Show Gist options
  • Save mathieuancelin/09abb6057f37cc5b331f4d16ecce8552 to your computer and use it in GitHub Desktop.
Save mathieuancelin/09abb6057f37cc5b331f4d16ecce8552 to your computer and use it in GitHub Desktop.
object JsonTest extends App {
object Implicits {
implicit final class EnhancedJsObject(obj: JsObject) {
def +?[A](tuple: (String, Option[A]))(implicit writes: Writes[A]): JsObject = {
tuple match {
case (key, Some(value)) => obj ++ Json.obj(key -> writes.writes(value))
case (key, None) => obj
}
}
def ++?[A](values: Seq[(String, Option[A])])(implicit writes: Writes[A]): JsObject = {
values.foldLeft(obj)((o, tuple) => o +? tuple)
}
}
}
import Implicits._
val opt1 = Some("yo")
val opt2 = Some(1234L)
val opt3: Option[String] = None
val opt4: Option[Integer] = None
val json = Json.obj(
"hello" -> "World",
"opt1" -> opt1,
"opt2" -> opt2
) ++? Seq(
"opt3" -> opt3
) +? (
"opt4" -> opt4
)
println(Json.prettyPrint(json))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment