gpt4 book ai didi

java - 使用 Scala 和 Jackson 以及 java.lang.Integer 或 scala.Int 对泛型类型进行奇怪的反序列化问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:42 24 4
gpt4 key购买 nike

我们都知道泛型类型在 Java 和 Scala 下会被类型删除。但是我们在使用 Jackson 和 Scala Jackson 模块的 Scala 中遇到了一个奇怪的问题。

我创建了一个小测试来展示这个问题。

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

object GenericTest {

case class TestWithInt(id: Option[Int])
case class TestWithInteger(id: Option[Integer])

def main(args: Array[String]) {

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

// Test with scala's Int
val test = mapper.readValue[TestWithInt]("""{ "id" : 5 }""", classOf[TestWithInt])
print("Test 1: ")
println(test.id.get + 1)

val test2 = mapper.readValue[TestWithInt]("""{ "id" : "5" }""", classOf[TestWithInt])
print("Test 2: ")
try {
println(test2.id.get + 1)
} catch {
case e: ClassCastException => println(e.getMessage)
}

// Test with java.lang.Integer
val test3 = mapper.readValue[TestWithInteger]("""{ "id" : 5 }""", classOf[TestWithInteger])
print("Test 3: ")
println(test3.id.get + 1)

val test4 = mapper.readValue[TestWithInteger]("""{ "id" : "5" }""", classOf[TestWithInteger])
print("Test 4: ")
println(test4.id.get + 1)
}
}

上面的输出是:

Test 1: 6
Test 2: java.lang.String cannot be cast to java.lang.Integer
Test 3: 6
Test 4: 6

这种不同类型的行为从何而来?通用类型删除、Jackson、Jackson Scala 模块?

最佳答案

这个问题变得如此普遍,以至于我写了一个 FAQ为此:

[A]ll primitive type parameters are represented as Object to the JVM. ... The Scala module has informed Jackson that Option is effectively a container type, but it relies on Java reflection to determine the contained type, and comes up with Object.

The current workaround for this use case is to add the @JsonDeserialize annotation to the member being targeted. Specifically, this annotation has a set of parameters that can be used for different situations:

  • contentAs for collections or map values (supported)
  • keyAs for Map keys (currently unsupported)

Examples of how to use this annotation can be found in the tests directory.

常见问题解答中有更多详细信息供好奇者使用。

关于java - 使用 Scala 和 Jackson 以及 java.lang.Integer 或 scala.Int 对泛型类型进行奇怪的反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19379967/

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