将自定义方法添加到JsonFormat

问题描述 投票:0回答:1

我有case class评分(所有评论总和的总和)和评论的数量(评论)

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将被忽略。请帮我解决这个问题

scala playframework
1个回答
0
投票

我已经解决了这个问题

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)) 
© www.soinside.com 2019 - 2024. All rights reserved.