- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 jackson-kotlin 集成。大多数情况下它工作得很好,但我在反序列化泛型类型时遇到了麻烦。我试图调整这个问题的答案:Jackson - Deserialize using generic class
// create an object mapper
val jsonFactory = JsonFactory()
jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)
jsonFactory.configure(JsonParser.Feature.IGNORE_UNDEFINED, true)
val objectMapper = ObjectMapper(jsonFactory)
objectMapper.findAndRegisterModules()
objectMapper.propertyNamingStrategy = PropertyNamingStrategy.SnakeCaseStrategy()
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
// simple generic type
data class Inner(val meaningOfLife: Int)
data class Outer<T>(val inner: T)
val outer = Outer(Inner(42))
val serialized = objectMapper.stringify(outer, true)
println(serialized)
// deserializing does not work using:
// https://stackoverflow.com/questions/11664894/jackson-deserialize-using-generic-class
val parsed = objectMapper.readValue<Outer<Inner>>(serialized, objectMapper.typeFactory.constructParametricType(Outer::class.java,Inner::class.java))
这会引发异常:
com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class io.inbot.common.ObjectMapperTest$should handle generics$Outer (of type local/anonymous) as a Bean
at [Source: (String)"{
"inner" : {
"meaning_of_life" : 42
}
}"; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:306)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:268)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:477)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4190)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4009)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3042)
at io.inbot.common.ObjectMapperTest.should handle generics(ObjectMapperTest.kt:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:580)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: java.lang.IllegalArgumentException: Cannot deserialize Class io.inbot.common.ObjectMapperTest$should handle generics$Outer (of type local/anonymous) as a Bean
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.isPotentialBeanType(BeanDeserializerFactory.java:877)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:131)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:411)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
... 31 more
显然 kotlin 的 jackson 插件不处理这个。是否有解决此问题的解决方法或其他方法?
顺便说一句。 stringify 函数是我为 ObjectMapper 添加的一个简单扩展函数,用于处理样板代码:
/**
* Serializes [value] to a string. Pretty prints if [pretty] is set.
*/
fun <T> ObjectMapper.stringify(value: T, pretty: Boolean = false): String {
val bos = ByteArrayOutputStream()
val writer = OutputStreamWriter(bos, StandardCharsets.UTF_8)
if(pretty) {
writerWithDefaultPrettyPrinter().writeValue(writer,value)
} else {
writeValue(writer, value)
}
writer.flush()
bos.flush()
return bos.toByteArray().toString(StandardCharsets.UTF_8)
}
更新 @jayson-minard 的答案中的代码有效。事实证明,与我的代码的主要区别在于我在测试方法中定义了数据类。将它们移到顶层可以解决问题。将数据类放在函数中一开始并不是一个好主意。
最佳答案
使用 Jackson 的 2.9.6
以及 Jackson 的主分支 2.9.8
以及当前的 Jackson-Kotlin 模块,我添加了这个通过的测试用例对于您的代码版本和代码的更简洁的惯用版本。
请注意,我也更新了 stringify
方法,使其更加地道,但这不会影响测试。
您对 readValue
的调用也比必要的更复杂。变化:
val parsed = objectMapper.readValue<Outer<Inner>>(serialized, objectMapper.typeFactory.constructParametricType(Outer::class.java, Inner::class.java))
简单地说:
val parsed = objectMapper.readValue<Outer<Inner>>(serialized)
这是完整的通过测试:
class TestStackOverflow53499407 {
data class Inner(val meaningOfLife: Int)
data class Outer<T>(val inner: T)
fun <T> ObjectMapper.stringify(value: T, pretty: Boolean = false): String {
StringWriter().use { writer ->
if (pretty) {
writerWithDefaultPrettyPrinter().writeValue(writer, value)
} else {
writeValue(writer, value)
}
return writer.toString()
}
}
@Test
fun test53499407_cleanTest() {
val outer = Outer(Inner(42))
val objectMapper = jacksonObjectMapper()
val serialized = objectMapper.stringify(outer, true)
println(serialized)
val parsed = objectMapper.readValue<Outer<Inner>>(serialized)
assertEquals(42, parsed.inner.meaningOfLife)
}
@Test
fun test53499407_idiomatic_tweek() {
val outer = Outer(Inner(42))
val jsonFactory = JsonFactory()
jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)
jsonFactory.configure(JsonParser.Feature.IGNORE_UNDEFINED, true)
val objectMapper = ObjectMapper(jsonFactory)
objectMapper.findAndRegisterModules()
objectMapper.propertyNamingStrategy = PropertyNamingStrategy.SnakeCaseStrategy()
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
val serialized = objectMapper.stringify(outer, true)
println(serialized)
// This line changed to be idiomatic
val parsed = objectMapper.readValue<Outer<Inner>>(serialized)
assertEquals(42, parsed.inner.meaningOfLife)
}
@Test
fun test53499407_as_written_in_stackoverflow() {
val outer = Outer(Inner(42))
val jsonFactory = JsonFactory()
jsonFactory.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)
jsonFactory.configure(JsonParser.Feature.IGNORE_UNDEFINED, true)
val objectMapper = ObjectMapper(jsonFactory)
objectMapper.findAndRegisterModules()
objectMapper.propertyNamingStrategy = PropertyNamingStrategy.SnakeCaseStrategy()
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
val serialized = objectMapper.stringify(outer, true)
println(serialized)
// deserializing does not work using:
// https://stackoverflow.com/questions/11664894/jackson-deserialize-using-generic-class
val parsed = objectMapper.readValue<Outer<Inner>>(serialized, objectMapper.typeFactory.constructParametricType(Outer::class.java, Inner::class.java))
assertEquals(42, parsed.inner.meaningOfLife)
}
}
关于generics - 使用 jackson-module-kotlin 反序列化通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53499407/
generic parameters of trait function 的简单示例: trait Ext: Sized { fn then(self, f: fn(Self) -> R) -
在下面的代码中,为什么 Groovy 似乎忽略了方法 barMany 中提供的闭包参数的泛型类型声明: import groovy.transform.CompileStatic @CompileSt
据我所知,Prolog 没有任何内置机制用于generic programming。 .可以使用统一来模拟泛型,但这需要在运行时进行类型检查: :- initialization(main). :-
在我的应用程序中,我有一个 Board。董事会由细胞组成。每个单元格都有一个 int 值。有几种类型的 Board 可以扩展 Board。每种类型的板将以不同方式表示单元格。例如,一个人会使用 Lis
我想将存储的属性添加到 UIView 子类中,例如UIView、UIImageView、UIPickerView等, 我只需要从子类创建 UIView 的实例子类仅类型不同,所有属性和方法都相同。 T
这个问题在这里已经有了答案: Any type and implementing generic list in go programming language (2 个答案) 关闭 6 个月前。
我有以下代码as seen in ideone.com : import java.util.*; class Test{ interface Visitor{ public
在 Swift 中,我们可以对序列等通用项编写扩展: extension Sequence where Iterator.Element : ObservableType { } 这将保证扩展仅适用于
我知道这听起来很困惑,但这是我能解释的最好的了。 (您可以建议一个更好的标题)。我有 3 节课:- A public class A > { ... } B public class B {
我目前在大学攻读 CS,我刚刚开始学习数据结构和算法类(class)。我的教授非常喜欢(实际上是强制我们)使用 Ada。为了取得成功,我开始查找一些东西并找到了这段代码,它描述了如何编写通用堆栈: g
我正在玩 Scala By Example 开头的 QuickSort 示例并尝试将其调整为通用类型 A ,而不仅仅是 Int s。 到目前为止我的工作是 def sort[A new Y(i, -
谁能解释为什么下面的第二个例子不能编译? “测试 2”给出“错误 FS0670:此代码不够通用。类型变量 ^a 无法泛化,因为它会超出其范围。”。我无法理解此错误消息。 // Test 1 type
如何将泛型存储在非泛型对象持有的泛型TList中? type TXmlBuilder = class type TXmlAttribute= class Name: Str
我正在尝试通过遵循 wiki article 创建如何使用 GHC.Generics 的最小工作示例.这是我所拥有的: {-# LANGUAGE DefaultSignatures, DeriveGe
我正在尝试将 get 函数添加到 wiki 中描述的通用序列化中。 。有些部分看起来很简单,但有一些地方我非常不确定要写什么,毫不奇怪,我遇到了编译错误。我已经查看了原始论文以及 cereal 中的实
为什么这段代码有效? $v):void { print_r($v); } test(Vector {1, array("I'm an array"), 3}); 它不应该抛出错误吗?什么是应
有没有办法让 Rust Generic 只接受原始类型?我想稍后迭代值中的位,并且我知道这只有在原始类型中才有可能。 struct MyStruct { my_property: T // m
假设我有一个简单的类 public class MyObject { } 以及处理MyObject子类的handler接口(interface) public interface MyObjectHa
出于某种原因,我正在努力通过使用通用基类来实现通用接口(interface)的属性,如下所示: public interface IParent where TChild : IChild {
我收到以下错误。 google了一天多,还是找不到具体的解决方法,求大神指点,谢谢 ERROR: Cannot implicitly convert type System.Collections.G
我是一名优秀的程序员,十分优秀!