首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向JsonFormat添加自定义方法

向JsonFormat添加自定义方法
EN

Stack Overflow用户
提问于 2019-03-29 22:18:57
回答 1查看 63关注 0票数 0

我有case class with score (所有评论分数之和)和count (评论数)。

代码语言:javascript
复制
case class Rating(score: Long = 0L, count: Int = 0) {
   def total():Long = if (count == 0) 0L else score/count;
}

并且我希望支持以下用于序列化的json格式

代码语言:javascript
复制
{
    "score": 100,
    "count": 11
}

并且在反序列化之后

代码语言:javascript
复制
{
    "score": 100,
    "count": 11,
    "total": 9
}

所以我想计算total并将其显示在反序列化的json中。如果是Json.format[ClassRating],将忽略total。请帮我解决这个问题

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-30 17:54:28

我已经解决了这个问题

代码语言:javascript
复制
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)) 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55419428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档