用于案例对象的Play Framework JSON格式(Play Framework JSON Format for Case Objects)

编程入门 行业动态 更新时间:2024-10-27 01:25:06
用于案例对象的Play Framework JSON格式(Play Framework JSON Format for Case Objects)

我有一组继承自特征的案例对象,如下所示:

sealed trait UserRole case object SuperAdmin extends UserRole case object Admin extends UserRole case object User extends UserRole

我想将其序列化为JSON,我只使用了Format机制:

implicit val userRoleFormat: Format[UserRole] = Json.format[UserRole]

但不幸的是,编译器不满意,它说:

No unapply or unapplySeq function found

我的案例对象出了什么问题?

I have a set of case objects that inherits from a trait as below:

sealed trait UserRole case object SuperAdmin extends UserRole case object Admin extends UserRole case object User extends UserRole

I want to serialize this as JSON and I just used the Format mechanism:

implicit val userRoleFormat: Format[UserRole] = Json.format[UserRole]

But unfortunately, the compiler is not happy and it says:

No unapply or unapplySeq function found

What is wrong in my case objects?

最满意答案

好的,我想出了必须要做的事情!

这里是:

implicit object UserRoleWrites extends Writes[UserRole] { def writes(role: UserRole) = role match { case Admin => Json.toJson("Admin") case SuperAdmin => Json.toJson("SuperAdmin") case User => Json.toJson("User") } }

Another option is to override def toString like this:

File: Status.scala

package models trait Status case object Active extends Status { override def toString: String = this.productPrefix } case object InActive extends Status { override def toString: String = this.productPrefix }

this.productPrefix will give you case object name

File: Answer.scala

package models import play.api.libs.json._ case class Answer( id: Int, label: String, status: Status ) { implicit val answerWrites = new Writes[Answer] { def writes(answer: Answer): JsObject = Json.obj( "id" -> answer.id, "label" -> answer.label, "status" -> answer.status.toString ) } def toJson = { Json.toJson(this) } }

File: Controller.scala

import models._ val jsonAnswer = Answer(1, "Blue", Active).toJson println(jsonAnswer)

you get:

{"id":1,"label":"Blue","status":"Active"}

Hope this helps!

更多推荐

本文发布于:2023-07-30 11:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1337880.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   案例   格式   Play   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!