我有case class with score (所有评论分数之和)和count (评论数)。
case class Rating(score: Long = 0L, count: Int = 0) {
def total():Long = if (count == 0) 0L else score/count;
}并且我希望支持以下用于序列化的json格式
{
"score": 100,
"count": 11
}并且在反序列化之后
{
"score": 100,
"count": 11,
"total": 9
}所以我想计算total并将其显示在反序列化的json中。如果是Json.format[ClassRating],将忽略total。请帮我解决这个问题
发布于 2019-03-30 17:54:28
我已经解决了这个问题
case class Rating(score: Long = 0L, count: Int = 0) {
def total: Long = if (count == 0) 0L else score / count
}
object Rating {
def apply(score: Long, count: Int): Rating = new Rating(score, count)
def unapply(x : Rating): Option[(Long, Int, Long)] = Some(x.score, x.count, x.total)
}
val classRatingReads: Reads[Rating] = (
(JsPath \ "score").read[Long] and
(JsPath \ "count").read[Int]
)(Rating.apply _)
val classRatingWrites: OWrites[Rating] = (
(JsPath \ "score").write[Long] and
(JsPath \ "count").write[Int] and
(JsPath \ "total").write[Long]
)(unlift(ClassRating.unapply)) https://stackoverflow.com/questions/55419428
复制相似问题