我有一些扩展此类的案例类:
class CitySuggestion(val name: String, val locationId: String, val locationKind: String)
我想将Json.writes[CitySuggestion]
用作此类的JSON编写器,因此我在其配套对象中定义了unapply
方法:
object CitySuggestion {
def unapply(cs: CitySuggestion): Option[(String, String, String)] =
Some((cs.name, cs.locationId, cs.locationKind))
}
我认为这样就足够了,但编译器现在也要求apply
方法:
未找到应用功能
[error]隐式lazy val citySuggestionWrites = Json.writes [CitySuggestion]
为什么需要申请方法?我不想反序列化JSON,我必须添加逻辑来确定应该反序列化的子类的实例。
答案 0 :(得分:1)
这是因为Play Json的writes
& reads
宏共享common implementation.在此实现中,为A
提供的Json.writes[A]
类型会检查其应用方法,而后者又用于生成申请Writes
1}}实例。
作为使用“写入”宏的替代方法,您可以像这样创建自己的Write[CitySuggestion]
:
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val citySuggestionWrites: Writes[CitySuggestion] = (
(JsPath \ "name").write[String] and
(JsPath \ "locationId").write[String] and
(JsPath \ "locationKind").write[String]
)(unlift(CitySuggestion.unapply))