简体   繁体   中英

Spring Jackson Serialization of Scala Enumeration

I'm trying to get spring though jackson to serialize my scala enum. From what i've been able to tell I need to follow this: https://github.com/FasterXML/jackson-module-scala/wiki/Enumerations

I'm useing Scala Version 2.12.6 and Spring Boot Version 2.0.3

My Enum looks like:

object MyEnum extends Enumeration {
    type MyEnum = Value
    val VALUE_1 = Value("Value 1")
    val VALUE_2 = Value("Value 2")
}

class MyEnumTypeReference extends TypeReference[MyEnum.type]

My Entity looks like:

@Entity
@Table(name = "TABLE", schema = "schema")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class MyEntity(var myId: String, var someOtherThing: String, @JsonScalaEnumeration(classOf[MyEnumTypeReference]) var myEnum: MyEnum.MyEnum) extends Serializable {
    def this() = this(null, null, null)
    def this(myId: String, myEnum: MyEnum.MyEnum) = this(myId, myEnum)

    // Getters and Setters
}

When I hit my spring endpoint that queries this entity I get:

[
    {
        "myId": "123456",
        "someOtherThing": "I'm a String",
        "myEnum": {}
    }
]

I've verified that the entity returned though my ReponseEntity in my controller contains a value for the enum. I can't figure out why the enum just has an empty object instead of the serialized object? Thanks in advance.

Edit: I've also tested it directly using the objectmapper that I set in my spring configuration and it serializes the enum correctly there. I also tried autowiring springs objectmapper in my controller and it serializes correctly there too.

Since I could not get this to work I had to go the route of using sealed trait and case classes to emulated the enum. This required updating my hibernate logic to something more complex, but I am now able to (de)serialize my enums for spring.

My new Enum:

sealed trait MyEnum extends Product with Serializable { def myEnum: String }

object MyEnum {
    case object VALUE_1 extends MyEnum { @JsonProperty("value") val myEnum = "Value 1" }
    case object VALUE_2 extends MyEnum { @JsonProperty("value") val myEnum = "Value 2" }

    def values(): List[MyEnum] = List(VALUE_1, VALUE_2)

    // Other Enum Functions
}

I also removed the @JsonScalaEnumeration from my entity since it no longer uses scala's Enumeration.

My Response now looks like:

[
    {
        "myId": "123456",
        "someOtherThing": "I'm a String",
        "myEnum": {
            "value": "Value 1"
        }
    }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM