play-json-extensions
play-json-extensions copied to clipboard
JsonConfiguration(SnakeCase) analogue?
Is there any way to automatically convert camel case fields to underscored?
For example:
case case Person(firstName: String, lastName: String)
object Person {
// will be used by format to map field names
implicit val jsonConfig = JsonConfiguration(SnakeCase)
implicit val format = Jsonx.formatCaseClass[Person]
}
Should produce:
{
"first_name": "...",
"last_name": "..."
}
I found some code in ai.x.play.json.SingletonEncoder but seems that it is used only in ai.x.play.json.Jsonx#formatSingleton
Hi @aaabramov!
I just tried to solve it here: https://github.com/xdotai/play-json-extensions/pull/74
Now to have names in snake case you can:
case class Person(firstName: String, lastName: String)
implicit val encoder: NameEncoder = CamelToSnakeNameEncoder()
implicit val format = Jsonx.formatCaseClass[Person]
val person = Person("...", "...")
println(Json.toJson(person))
{ "first_name": "...", "last_name": "..." }
Due to the fact that macros does not support default/named arguments, for standard camel format implicit is also required. This solves the import:
import ai.x.play.json.Encoders._