0

我有那行代码,它在那个版本上工作:

...
Wrapper<Model> wrapped = restTemplate.getForObject(BASE_URL, Wrapper.class, map);
...

但是我想将参数发送给构造函数:

...
Wrapper<Model> wrapped = restTemplate.getForObject(BASE_URL, new Wrapper(Model.class).getClass(), map);
...

它给我一个例外:

org.springframework.web.client.ResourceAccessException: I/O error: No suitable constructor found for type [simple type, class a.b.c.d.model.Wrapper]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: org.apache.commons.httpclient.AutoCloseInputStream@ef9e8eb; line: 1, column: 3]; nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class a.b.c.d.model.Wrapper]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: org.apache.commons.httpclient.AutoCloseInputStream@ef9e8eb; line: 1, column: 3]

如何将参数发送到我将获得它的值类的对象?

4

2 回答 2

1

Wrapper.class并返回相同的值new Wrapper().getClass():. 如果你有合适的构造函数,即能够获取参数的构造函数,所有这一切。在您的情况下,类没有接受 type 参数的构造函数,因此它抱怨这一点。new Wrapper(theParam).getClass()Wrapper.classtheParamWrapperClass

于 2011-11-15T09:28:23.670 回答
0

我假设您需要的是指示杰克逊使用的通用包装器类型。有几种方法可以做到这一点:

Wrapper<Model> value = objectMapper.readValue(source, new TypeReference<Wrapper<Model>>() { });
Wrapper<Model> value = objectMapper.readValue(source, objectMapper.getTypeFactory().constructParametricType(Wrapper.class, Model.class);

我不确定 TypeReference 或 JavaType(它们是启用泛型的替代方法,可以替代传递 Class 实例(类型擦除,即没有泛型!))如何通过 Spring 框架,但我认为它应该是可能的。

或者,如果这不起作用,请尝试对 Wrapper 进行子类化——具体的子类实际上将具有必要的信息:

公共类 ModelWrapper 扩展 Wrapper { } ModelWrapper 包装 = restTemplate.getForObject(BASE_URL, ModelWrapper.class);

于 2011-11-15T16:38:24.203 回答