scala - 将自定义方法添加到 JsonFormat
问题描述
我有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
会被忽略。请帮我解决这个问题
解决方案
我已经解决了这个问题
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))
推荐阅读
- go - 如何同时打印和扫描
- java - Hashmap 中的值增量
- groovy - Geb Page对象方法在黄瓜步骤实现中不可访问
- nativescript - Nativescript Vue RadSideDrawer 未定义
- javascript - 在 PHP 中获取 JSON 时在 Vue 中添加加载指示器
- optimization - 优化 PL/SQL 过滤器
- javascript - Javascript视频暂停不是功能
- javascript - 传递级联下拉列表项 Web 控制器的文本值
- javascript - for循环内的异步函数
- apache-kafka - kafka堆内存大小取决于哪些因素?