Last active
December 14, 2015 14:29
-
-
Save afternoon/5100625 to your computer and use it in GitHub Desktop.
Easily serialise any object to JSON in Scala via an implicit conversion.
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
| /* | |
| * 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