Skip to content

Instantly share code, notes, and snippets.

@salomvary
Last active December 25, 2015 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salomvary/6898825 to your computer and use it in GitHub Desktop.
Save salomvary/6898825 to your computer and use it in GitHub Desktop.
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import scala.collection.JavaConversions._
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true)
mapper.readValue("""{"bar":{"title":"hello"}}""", classOf[Map[String, Any]])
// res4: Map[String,Any] = Map(bar -> Map(title -> hello))
case class Bar(title: String)
case class Foo(bar: Bar)
mapper.readValue("""{"bar":{"title":"hello"}}""", classOf[Foo])
// res5: Foo = Foo(Bar(hello))
case class Baz(title:Option[String])
mapper.readValue("""{}""", classOf[Baz])
// res5: Baz = Baz(None)
mapper.readValue("""{"title":"hello"}""", classOf[Baz])
// res6: Baz = Baz(Some(hello))
mapper.readValue("""{"title":null}""", classOf[Baz])
// res7: Baz = Baz(None)
mapper.readValue("""{"title":"hello", "unexpected": true}""", classOf[Baz])
// exception
import com.fasterxml.jackson.databind.DeserializationFeature
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.readValue("""{"title":"hello", "unexpected": true}""", classOf[Baz])
// res33: Baz = Baz(Some(hello))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment