Skip to content

Instantly share code, notes, and snippets.

@johnynek
Last active December 23, 2015 18:09
Show Gist options
  • Save johnynek/6674286 to your computer and use it in GitHub Desktop.
Save johnynek/6674286 to your computer and use it in GitHub Desktop.
Json injection example with case classes to Maps.
scala> case class Wrapped(x: Int, y: Long)
defined class Wrapped
scala> import com.twitter.bijection._
import com.twitter.bijection._
scala> import com.twitter.bijection.json._
import com.twitter.bijection.json._
scala> import com.twitter.bijection.json.JsonNodeInjection._
import com.twitter.bijection.json.JsonNodeInjection._
scala> import org.codehaus.jackson.{JsonParser, JsonNode, JsonFactory}
import org.codehaus.jackson.{JsonParser, JsonNode, JsonFactory}
scala> implicit val inj1 = Injection.build[Wrapped, Map[String, JsonNode]] { w =>
Map("x" -> toJsonNode(w.x), "y" -> toJsonNode(w.y)) } { m =>
scala.util.Try(Wrapped(fromJsonNode[Int](m("x")).get, fromJsonNode[Long](m("y")).get))
}
inj1: com.twitter.bijection.Injection[Wrapped,Map[String,org.codehaus.jackson.JsonNode]] = com.twitter.bijection.Injection$$anon$5@73dd5309
scala> implicit val mapTo = JsonInjection.toString[Map[String, JsonNode]]
mapTo: com.twitter.bijection.Injection[Map[String,org.codehaus.jackson.JsonNode],String] = com.twitter.bijection.Injection$$anon$1@37203d56
scala> val inj2 = Injection.connect[Wrapped, Map[String, JsonNode], String]
inj2: com.twitter.bijection.Injection[Wrapped,String] = com.twitter.bijection.Injection$$anon$1@61d8186c
scala> inj2(Wrapped(1, 3L))
res1: String = {"x":1,"y":3}
scala> inj2.invert(res1)
res2: scala.util.Try[Wrapped] = Success(Wrapped(1,3))
@zzztimbo
Copy link

How would I go about doing this with a nested case class? E.g.

case class Person(name: String, age: String)
case class Employee(title: String, person: Person)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment