我已经阅读过Neal Gafter关于这个主题的博客,但我仍然不清楚其中的一些观点.
为什么在给定Java的当前状态,JVM和现有集合API的情况下,不可能创建保留类型信息的Collections API的实现?难道这些不能以保留向后兼容性的方式替换未来Java版本中的现有实现吗?
举个例子:
List<T> list = REIList<T>(T.Class);
Run Code Online (Sandbox Code Playgroud)
REIList是这样的:
public REIList<T>() implements List {
private Object o;
private Class klass;
public REIList(Object o) {
this.o = o;
klass = o.getClass();
}
... the rest of the list implementation ...
Run Code Online (Sandbox Code Playgroud)
并且这些方法使用Object o和Class klass来获取类型信息.
为什么保留泛型类信息需要语言更改而不仅仅是JVM实现更改?
我不明白的是什么?
反序列化以下JSON的正确语法是什么:
[ {
"id" : "1",
"name" : "Blues"
}, {
"id" : "0",
"name" : "Rock"
} ]
Run Code Online (Sandbox Code Playgroud)
我试过了:
//Works OK
val dtos = mapper.readValue(json, List::class.java)
Run Code Online (Sandbox Code Playgroud)
不过我想:
val dtos : List<GenreDTO> = mapper.readValue(json,
List<GenreDTO>::class.java)
Run Code Online (Sandbox Code Playgroud)
上面的语法不正确,并给出: only classes are allowed on the left hand side of a class literal
想象一下以下场景:
class <T> Foo<T> {
....
}
class Bar {
Foo<Something> foo;
}
Run Code Online (Sandbox Code Playgroud)
我想为Foo编写一个自定义Jackson解串器.为了做到这一点(例如,为了反序列化Bar具有类Foo<Something>属性),我需要知道具体类型的Foo<T>,在使用Bar,在反序列化时间(比如我需要知道T是Something在particluar情况下).
如何编写这样的解串器?应该可以这样做,因为杰克逊用类型集合和地图来做.
澄清:
似乎有2个部分来解决问题:
1)获取foo内部声明的属性类型Bar并使用它来反序列化Foo<Somehting>
2)在反序列化时找出我们正在对foo类内的属性进行反序列化Bar以便成功完成步骤1)
如何完成1和2?
我正在使用spring-boot和Kotlin开发REST服务.(我应该提到这是我第一次使用它们.)我无法使用此代码让Jackson从POST请求中反序列化JSON:
@RequestMapping("cloudservice/login/{uuid}", method = arrayOf(RequestMethod.POST))
fun login(@PathVariable(value="uuid")uuid: String, @RequestBody user: CloudServiceUser ) : ResponseEntity<CloudServiceUser> {
val cloudServiceFactory : Class<CloudServiceFactory> = cloudServiceRepository.cloudServiceExtensions[UUID.fromString(uuid)] ?: throw InvalidPathVariableException("Invalid UUID.")
var token : String
try {
token = cloudServiceFactory.newInstance().authenticationService.login(user.userId, user.password)
} catch (e:Exception ){
throw CloudServiceException(e.message)
}
return ResponseEntity(CloudServiceUser(userId=user.userId, password = "", token = token),HttpStatus.OK)
}
Run Code Online (Sandbox Code Playgroud)
用户对象很简单:
data class CloudServiceUser(val userId: String, val password:String, val token:String)
Run Code Online (Sandbox Code Playgroud)
我收到了错误
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.irotsoma.cloudbackenc.cloudservice.CloudServiceUser: no suitable constructor found, can not deserialize …Run Code Online (Sandbox Code Playgroud) jackson ×3
generics ×2
java ×2
json ×2
kotlin ×2
collections ×1
jvm ×1
reification ×1
rest ×1
spring-boot ×1