Использование разных стратегий JsonNaming для разных классов дел в игре scala - PullRequest
0 голосов
/ 27 марта 2020

У меня есть два разных JSON сообщения, которые я хочу превратить в экземпляры классов дел.

case class ThisThing(attributeOne: String)
case class ThatThing(attributeTwo: String)

implicit val config: Aux[Json.MacroOptions] = JsonConfiguration(SnakeCase)
implicit val thisThingFormat: OFormat[ThisThing] = Json.format[ThisThing]
implicit val thatThingFormat: OFormat[ThatThing]= Json.format[ThatThing]

Теперь я могу анализировать сообщения типа:

val thisThing = Json.fromJson[ThisThing](Json.parse("{\"attribute_one\": \"hurray\"}"))

Однако мои ThatThing JSON сообщения не заключены в змеи, их атрибуты соответствуют классу случая:

val thatThing = Json.fromJson[ThatThing](Json.parse("{\"attributeTwo\": \"hurray\"}"))

Это выдает ошибку, так как ищет атрибут с именем attribute_two для сопоставления с attributeTwo.

Как указать стратегию именования SnakeCase только для определенных классов дел

1 Ответ

1 голос
/ 27 марта 2020

Как и любой implicit, конфигурация может быть ограничена:

import play.api.libs.json._

case class ThisThing(attributeOne: String)
case class ThatThing(attributeTwo: String)

implicit val thisThingFormat: OFormat[ThisThing] = {
  implicit val config = JsonConfiguration(JsonNaming.SnakeCase)

  Json.format[ThisThing]
}

implicit val thatThingFormat: OFormat[ThatThing] = Json.format[ThatThing]

Тогда:

Json.fromJson[ThisThing](Json.parse("{\"attribute_one\": \"hurray\"}"))
// res0: play.api.libs.json.JsResult[ThisThing] = JsSuccess(ThisThing(hurray),)

Json.fromJson[ThatThing](Json.parse("{\"attributeTwo\": \"hurray\"}"))
// res1: play.api.libs.json.JsResult[ThatThing] = JsSuccess(ThatThing(hurray),)
...