Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serialization of Scala enums using Jackson

Tags:

jackson

scala

Following this article https://github.com/FasterXML/jackson-module-scala/wiki/Enumerations

The enumeration declaration is as

object UserStatus extends Enumeration {
  type UserStatus = Value
  val Active, Paused = Value
}

class UserStatusType extends TypeReference[UserStatus.type]
case class UserStatusHolder(@JsonScalaEnumeration(classOf[UserStatusType]) enum:   UserStatus.UserStatus)

The DTO is declared as

class UserInfo(val emailAddress: String, val  userStatus:UserStatusHolder) {

}

and the serialization code is

val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

def serialize(value: Any): String = {
    import java.io.StringWriter
    val writer = new StringWriter()
    mapper.writeValue(writer, value)
    writer.toString
}

The resulting JSON serialization is

{
    "emailAddress":"[email protected]",
    "userStatus":{"enum":"Active"}
}

Is it possible to get it the following form ?

{
    "emailAddress":"[email protected]",
    "userStatus":"Active"
}
like image 962
np-hard Avatar asked Jul 23 '15 18:07

np-hard


People also ask

Does Jackson use serializable?

Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.

How do you serialize an enum?

In order to serialize Enum, we take the help of ObjectMapper class. We use the writeValueAsString() method of ObjectMapper class for serializing Enum. If we serialize Enum by using the writeValueAsString() method, it will represent Java Enums as a simple string.

How do I pass enum as JSON?

All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .


1 Answers

Have you tried:

case class UserInfo(
   emailAddress: String, 
   @JsonScalaEnumeration(classOf[UserStatusType]) userStatus:   UserStatus.UserStatus
)

The jackson wiki's example is a little misleading. You don't need the holder class. Its just an example of a thing that has that element. The thing you need is the annotation

like image 63
devshorts Avatar answered Nov 08 '22 19:11

devshorts