Skip to content

Instantly share code, notes, and snippets.

@cspinetta
Created November 20, 2018 15:15
Show Gist options
  • Save cspinetta/fcab30ffd69a5b2d2644d3782f31add4 to your computer and use it in GitHub Desktop.
Save cspinetta/fcab30ffd69a5b2d2644d3782f31add4 to your computer and use it in GitHub Desktop.
Jackson ObjectMapper
package base.serializer
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility
import com.fasterxml.jackson.annotation.{JsonInclude, PropertyAccessor}
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import play.api.libs.json.{JsValue, Json}
import play.api.libs.json.jackson.PlayJsonModule
object SnakeCaseSerializer extends SnakeCaseSerializer(Nil) {
implicit class JsonString(val json: String) extends AnyVal {
def as[T: Manifest]: T = read(json)
}
implicit class AnyJsonizable(val someObject: Any) extends AnyVal {
def asJson: String = write(someObject)
def asJsValue: JsValue = Json.parse(asJson)
}
}
trait Serializer {
def read[T](value: String)(implicit mf: Manifest[T]): T
def write(obj: Any): String
}
class SnakeCaseSerializer(customModules: List[Module]) extends Serializer {
private val objectMapper: ObjectMapper with ScalaObjectMapper = {
val m = new ObjectMapper() with ScalaObjectMapper
m.registerModule(new DefaultScalaModule)
m.registerModule(PlayJsonModule)
m.registerModules(customModules:_*)
m.registerModule(new Jdk8Module())
m.registerModule(new JavaTimeModule())
m.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
m.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, true)
m.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
m.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
m.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
m.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
m.setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
m.setVisibility(PropertyAccessor.ALL, Visibility.NONE)
m.setVisibility(PropertyAccessor.FIELD, Visibility.ANY)
m
}
def write(obj:Any):String = objectMapper.writeValueAsString(obj)
def read[T](json: String)(implicit mf: Manifest[T]):T = objectMapper.readValue[T](json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment