Scala 单一属性案例类的JSON格式
给定 为Scala 单一属性案例类的JSON格式,scala,playframework,play-json,Scala,Playframework,Play Json,给定 为ResidentJSON格式编写器的最简单方法是什么 我正在尝试使用FunctionalBuilder case class Location(lat: Double, long: Double) case class Resident(location: Location) 但是将它与单个属性案例类一起使用是不容易的。我随后的尝试倾向于涉及比我认为必要的更多的代码 希望您能提供一些提示,请使用: val residentFormats: Format[Resident] = ( (J
Resident
JSON格式编写器的最简单方法是什么
我正在尝试使用FunctionalBuilder
case class Location(lat: Double, long: Double)
case class Resident(location: Location)
但是将它与单个属性案例类一起使用是不容易的。我随后的尝试倾向于涉及比我认为必要的更多的代码
希望您能提供一些提示,请使用:
val residentFormats: Format[Resident] = (
(JsPath \ "location").format[Location]
) (Resident.apply, unlift(Resident.unapply))
也可以拆分定义:
object Resident {
implicit val format: OFormat[Resident] = Json.format[Resident]
}
您可以自己定义读取
和写入:
object Resident {
implicit val reads: Reads[Resident] = Json.reads[Resident]
implicit val writes: OWrites[Resident] = Json.writes[Resident]
}
注意:如果需要将名称从camelCase转换为下划线键,可以定义隐式JsonConfiguration
:
object Resident {
implicit val reads: Reads[Resident] = json => {
(json \ "location").validate[Location].map(Resident(_))
}
implicit val writes: OWrites[Resident] = resident => Json.obj("localtion" -> resident.location)
}
只需使用:
val residentFormats: Format[Resident] = (
(JsPath \ "location").format[Location]
) (Resident.apply, unlift(Resident.unapply))
也可以拆分定义:
object Resident {
implicit val format: OFormat[Resident] = Json.format[Resident]
}
您可以自己定义读取
和写入:
object Resident {
implicit val reads: Reads[Resident] = Json.reads[Resident]
implicit val writes: OWrites[Resident] = Json.writes[Resident]
}
注意:如果需要将名称从camelCase转换为下划线键,可以定义隐式JsonConfiguration
:
object Resident {
implicit val reads: Reads[Resident] = json => {
(json \ "location").validate[Location].map(Resident(_))
}
implicit val writes: OWrites[Resident] = resident => Json.obj("localtion" -> resident.location)
}
您将如何阅读以下格式的JSON键
Location
,ResidentLocation
,我想我必须编写一个自定义的JsonConfiguration
?感谢您指出JsonConfiguration
方面,顺便说一下,我从未使用过它@ivanorone最好在单独的问题中询问有关自定义命名的问题,以便其他用户更容易找到答案。创建一个问题并给我发一个链接@Andrii Abramov,是的,但是,这实际上是一些次要的东西,我在第二次看的时候发现了。我想我不需要就此提出任何问题。下次我会记住你说的话。以下人士:object Capitalize扩展了JsonNaming{def apply(property:String):String=property.Capitalize;override val toString=“Capitalize”}
@ivanorone是的,没错!然后将其作为功能工厂传递给JsonConfiguration
JsonNaming(uu.capitalize)
,您将如何阅读以下格式的JSON键Location
,ResidentLocation
,我想我必须编写一个自定义的JsonConfiguration
?感谢您指出JsonConfiguration
方面,顺便说一下,我从未使用过它@ivanorone最好在单独的问题中询问有关自定义命名的问题,以便其他用户更容易找到答案。创建一个问题并给我发一个链接@Andrii Abramov,是的,但是,这实际上是一些次要的东西,我在第二次看的时候发现了。我想我不需要就此提出任何问题。下次我会记住你说的话。以下人士:object Capitalize扩展了JsonNaming{def apply(property:String):String=property.Capitalize;override val toString=“Capitalize”}
@ivanorone是的,没错!然后将其作为功能工厂传递给JsonConfiguration
JsonNaming(u.capitalize)