gpt4 book ai didi

启用 DefaultTyping 时,Scala 枚举序列化使用 Jackson 失败

转载 作者:行者123 更新时间:2023-12-04 10:46:14 41 4
gpt4 key购买 nike

我看到当 DefaultTyping 启用了 OBJECT_AND_NON_CONCRETE 时,Jackson 库无法序列化 Scala 枚举。环境。请注意,当我使用 JAVA_LANG_OBJECT 时,序列化工作正常环境。

我看到以下异常

[scalatest]   com.fasterxml.jackson.databind.JsonMappingException: Type id handling not implemented for type scala.Enumeration$Val (by serializer of type com.fasterxml.jackson.module.scala.ser.EnumerationSerializer) (through reference chain: <MyType>)
[scalatest] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284)
[scalatest] at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110)
[scalatest] at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135)
[scalatest] at com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:160)
[scalatest] at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:706)
[scalatest] at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689)
[scalatest] at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
[scalatest] at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
[scalatest] at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:2509)
[scalatest] at com.fasterxml.jackson.core.base.GeneratorBase.writeObject(GeneratorBase.java:378)

这是一个示例代码
  object Day extends Enumeration {
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}

case class Holiday(day: Day.Value)

val objectMapper = new ObjectMapper()
objectMapper.registerModule(DefaultScalaModule)
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false)
objectMapper.enableDefaultTyping(DefaultTyping.OBJECT_AND_NON_CONCRETE, JsonTypeInfo.As.PROPERTY)

我试过使用 @JsonScalaEnumerationhttps://github.com/FasterXML/jackson-module-scala/wiki/Enumerations 中所述,但似乎没有帮助。

提前致谢。

最佳答案

我用这样的解决方法让它工作

  object Day extends Enumeration {
type Day = Value
//val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
case class Val(dayName: String) extends super.Val

val Mon = Val("Monday")
val Tue = Val("Tuesday")
val Sat = Val("Saturday")
val Sun = Val("Sunday")
}

class DayType extends TypeReference[Day.type]

case class Holidays(@JsonScalaEnumeration(classOf[DayType]) days: Day.Val)

关于启用 DefaultTyping 时,Scala 枚举序列化使用 Jackson 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59690138/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com