将自定义方法添加到JsonFormat

时间:2019-03-29 14:18:57

标签: scala playframework

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

1 个答案:

答案 0 :(得分: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))