Created
October 18, 2014 13:43
-
-
Save maji-KY/836dab8cb63038f915aa to your computer and use it in GitHub Desktop.
json4sでcase classをJSONにシリアライズするときにキーをスネークケースにしたい
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
println(myWritePretty(foo)) | |
/* | |
以下が結果。 | |
Mapの中身のStringのキーも変換される。 | |
{ | |
"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