Skip to content

Instantly share code, notes, and snippets.

@sritchie
Created September 19, 2013 15:26
Show Gist options
  • Save sritchie/6625178 to your computer and use it in GitHub Desktop.
Save sritchie/6625178 to your computer and use it in GitHub Desktop.
import com.twitter.bijection._
import com.twitter.bijection.json.JsonInjection
import com.twitter.bijection.json.JsonNodeInjection._ // implicits required for building up JsonInjections from primitives
// Here's some custom case class that we'd like to be able to serialize into Json.
case class Wrapper(x: Int, y: Long)
// Now, we define a Bijection from our case class to a tuple.
val wrapperToTuple = Bijection.build[Wrapper, (Int, Long)](Wrapper.unapply(_).get)(Wrapper.tupled(_))
// Next we'll compose this with the library-supplied injection from Product -> String provided by JsonInjection:
val wrapperToString: Injection[Wrapper,String] = wrapperToTuple.andThen(JsonInjection.toString[(Int, Long)])
// Forward gets us to string, always:
val json: String = wrapperToString(Wrapper(10, 11L)) // String = [10,11]
// Invert returns a try:
wrapperToString.invert(Wrapper(10, 11L)) // scala.util.Try[Wrapper] = Success(Wrapper(10,11))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment