Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Standard format for Enumeration #200

Open
dskrvk opened this issue Oct 13, 2016 · 4 comments
Open

Standard format for Enumeration #200

dskrvk opened this issue Oct 13, 2016 · 4 comments

Comments

@dskrvk
Copy link

dskrvk commented Oct 13, 2016

Would it be useful to provide a standard format for values of an arbitrary Enumeration type?

I have a working implementation, though it relies on an implicit type evidence of the specific enum type provided by the user. I could use reflection instead, but that seems less desirable.

@dkowis
Copy link

dkowis commented May 25, 2017

I'd like to see said implementation, even if it's not part of the project, I could use it :)

@dkowis
Copy link

dkowis commented May 25, 2017

Since I ended up finding this after digging around on the internet for an example, I'll paste the example I found

import spray.json.{DeserializationException, JsString, JsValue, RootJsonFormat}

/**
  * Based on the code found: https://groups.google.com/forum/#!topic/spray-user/RkIwRIXzDDc
  */
class EnumJsonConverter[T <: scala.Enumeration](enu: T) extends RootJsonFormat[T#Value] {
  override def write(obj: T#Value): JsValue = JsString(obj.toString)

  override def read(json: JsValue): T#Value = {
    json match {
      case JsString(txt) => enu.withName(txt)
      case somethingElse => throw DeserializationException(s"Expected a value from enum $enu instead of $somethingElse")
    }
  }
}

Use like:

implicit val enumConverter = new EnumJsonConverter(YourEnum)

@davideicardi
Copy link

@dkowis I have created a PR, #336, based on your code to add it as an example.

@waagnermann
Copy link

@dkowis I have created a PR, #336, based on your code to add it as an example.

But it's not PR to code itself, it's just PR to README.md :)
Can collaborators introduce this feature (support for Enumeration formats) in future updates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants