play-json-extensions icon indicating copy to clipboard operation
play-json-extensions copied to clipboard

JsonConfiguration(SnakeCase) analogue?

Open aaabramov opened this issue 7 years ago • 1 comments

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

aaabramov avatar Feb 09 '18 12:02 aaabramov

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

mtsokol avatar Jul 09 '19 13:07 mtsokol