斯卡拉枚举的Spring Jackson序列化

问题描述 投票:1回答:1

我试图通过杰克逊获得春天来序列化我的scala enum。从我能够告诉我需要遵循这个:https://github.com/FasterXML/jackson-module-scala/wiki/Enumerations

我正在使用Scala版本2.12.6和Spring Boot版本2.0.3

我的Enum看起来像:

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]

我的实体看起来像:

@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
}

当我点击查询该实体的spring端点时,我得到:

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

我已验证通过我的控制器中的ReponseEntity返回的实体包含枚举值。我无法弄清楚为什么枚举只有一个空对象而不是序列化对象?提前致谢。

编辑:我也使用我在spring配置中设置的objectmapper直接测试它,并在那里正确序列化枚举。我也尝试在我的控制器中自动装配弹簧对象映射器,它也在那里正确序列化。

scala hibernate spring-boot enums jackson
1个回答
0
投票

由于我无法使用它,我不得不采用密封特性和案例类来模拟枚举。这需要将我的hibernate逻辑更新为更复杂的东西,但我现在能够(de)将我的枚举序列化为spring。

我的新枚举:

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
}

我还从我的实体中删除了@JsonScalaEnumeration,因为它不再使用scala的Enumeration。

我的回复现在看起来像:

[
    {
        "myId": "123456",
        "someOtherThing": "I'm a String",
        "myEnum": {
            "value": "Value 1"
        }
    }
]
© www.soinside.com 2019 - 2024. All rights reserved.