bizzabo / play-json-extensions

+22 field case class formatter and more for play-json
http://cvogt.org/play-json-extensions/api/
Other
196 stars 44 forks source link

JsonConfiguration(SnakeCase) analogue? #47

Open aaabramov opened 6 years ago

aaabramov commented 6 years ago

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

mtsokol commented 5 years ago

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._