繁体   English   中英

Spring Jackson Scala枚举的序列化

[英]Spring Jackson Serialization of Scala Enumeration

我试图通过杰克逊获得春天来序列化我的scala枚举。 从我已经告诉我的内容来看,我需要遵循以下步骤: https : //github.com/FasterXML/jackson-module-scala/wiki/Enumerations

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

我的枚举看起来像:

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直接测试了它,并在那里正确地枚举了枚举。 我还尝试在控制器中自动装配springs objectmapper,并且在那里也可以正确地序列化。

由于我无法执行此操作,因此我不得不采用密封的特征和案例类来模拟枚举的方法。 这需要将休眠逻辑更新为更复杂的内容,但是现在我可以对春天的枚举进行反序列化。

我的新枚举:

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"
        }
    }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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