Skip to content

Instantly share code, notes, and snippets.

View anuragsrivastava06's full-sized avatar

Anurag Srivastava anuragsrivastava06

  • Knoldus Software LLP
  • New Delhi
View GitHub Profile
View OptionWriter.scala
implicit def optionWriter[A]
(implicit writer: JsonWriter[A]): JsonWriter[Option[A]] =
new JsonWriter[Option[A]] {
def write(option: Option[A]): Json =
option match {
case Some(aValue) => writer.write(aValue)
case None => JsNull
View ExceptionExample.scala
implicit val writer1: JsonWriter[String] = JsonWriterInstances.stringWriter
implicit val writer2: JsonWriter[String] = JsonWriterInstances.stringWriter
Json.toJson("A string")
<console>:27: error: ambiguous implicit values:
both value stringWriter in object JsonWriterInstances of type => JsonWriter[String]
and value writer1 of type => JsonWriter[String]
match expected type JsonWriter[String]
View ExampleJsonSyntax.scala
import JsonWriterInstances._
import JsonSyntax._
Person("Dave", "").toJson
// res6: Json = JsObject(Map(name -> JsString(Dave), email -> JsString(
View JsonSyntax.scala
object JsonSyntax {
implicit class JsonWriterOps[A](value: A) {
def toJson(implicit w: JsonWriter[A]): Json =
View Example.scala
import JsonWriterInstances._
Json.toJson(Person("Dave", ""))
//res1: Json = JsObject(Map(name -> JsString(Dave), email -> JsString(
View Json.scala
object Json {
def toJson[A](value: A)(implicit w: JsonWriter[A]): Json = w.write(value)
View JsonWriterInstances.scala
final case class Person(name: String, email: String)
object JsonWriterInstances {
implicit val stringWriter: JsonWriter[String] =
new JsonWriter[String] {
def write(value: String): Json = JsString(value)
implicit val personWriter: JsonWriter[Person] =
new JsonWriter[Person] {
View JsonWriter.scala
sealed trait Json
final case class JsObject(get: Map[String, Json]) extends Json
final case class JsString(get: String) extends Json
final case class JsNumber(get: Double) extends Json
case object JsNull extends Json