Skip to content

Instantly share code, notes, and snippets.

Created October 18, 2014 13:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save maji-KY/836dab8cb63038f915aa to your computer and use it in GitHub Desktop.
json4sでcase classをJSONにシリアライズするときにキーをスネークケースにしたい
import org.json4s.jackson.{JsonMethods, Serialization}
import org.json4s.{Extraction, Formats, NoTypeHints}
object JsonTest extends App {
// Extraction.decomposeでJSON ASTを組み立てている
// んで、それにはsnakizeKeysってメソッドがあるのでそれを使えばスネークケースになる
def myWrite[A <: AnyRef](a: A)(implicit formats: Formats): String = JsonMethods.mapper.writeValueAsString(Extraction.decompose(a)(formats).snakizeKeys)
// プリティ☆バージョン
def myWritePretty[A <: AnyRef](a: A)(implicit formats: Formats): String = JsonMethods.mapper.writerWithDefaultPrettyPrinter.writeValueAsString(Extraction.decompose(a)(formats).snakizeKeys)
case class FooClass(someValue: String, nestedMap: Map[String, String])
val foo = FooClass("Hello World", Map("fooBarBaz" -> "fooBarBaz", "StringMessage" -> "hello"))
implicit val formats = Serialization.formats(NoTypeHints)
"some_value" : "Hello World",
"nested_map" : {
"foo_bar_baz" : "fooBarBaz",
"string_message" : "hello"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment