Skip to content

Instantly share code, notes, and snippets.

@afternoon
Last active December 14, 2015 14:29
Show Gist options
  • Select an option

  • Save afternoon/5100625 to your computer and use it in GitHub Desktop.

Select an option

Save afternoon/5100625 to your computer and use it in GitHub Desktop.
Easily serialise any object to JSON in Scala via an implicit conversion.
/*
* Usage:
*
* import com.ben2.jsonops.Implicits._
* val obj = makeSomeObject()
* println(obj.toJson)
*/
package com.ben2.jsonops
import com.fasterxml.jackson.databind.{Module, ObjectMapper, SerializationFeature}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
// render arbitrary objects to JSON using Jackson
class JsonOps(val obj: Any) {
def mapper = {
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
mapper
}
def toJson: String = mapper.writeValueAsString(obj)
}
object Implicits {
implicit def anyToJsonOps(obj: Any): JsonOps = new JsonOps(obj)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment