2017-12-27 374 views
0

我有一个REST回调服务必须按以下格式使用XML:Spring REST:适用于嵌套XML请求正文的构造函数吗?

<SearchRequest> 
    <SearchCriteria> 
    <Param1></Param2> 
    <Param2></Param2> 
    </SearchCriteria> 
</SearchRequest> 

实际的XML具有“标准”的范围内约32个参数,但是这给了基本思路。

我创建了一个SearchRequest类,它具有属性searchCriteria和具有param1和param2的SearchCriteria类。

我的REST控制器类看起来是这样的:

import org.springframework.beans.factory.annotation.Value; 
import org.springframework.http.HttpStatus; 
import org.springframework.http.ResponseEntity; 
import org.springframework.web.bind.annotation.RequestBody; 
import org.springframework.web.bind.annotation.RequestHeader; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

@RestController 
@RequestMapping("/acme/request/search") 
public class AcmeCallbackController { 
    @RequestMapping(method = RequestMethod.POST, consumes = "application/xml") 
    public ResponseEntity<String> postAcmeSearch(@RequestBody SearchRequest body) { 
     StringBuffer resultBuffer = new StringBuffer(2048); 
     // implementation code here, 'body' now expected to be a SearchRequest object contructed from request body XML 
     return new ResponseEntity<String>(resultBuffer.toString(), HttpStatus.OK); 
    } 

当我测试上面的服务,我收到以下错误响应:

`{ "timestamp": 1514390248822, 
"status": 400, 
"error": "Bad Request", 
"exception": org.springframework.http.converter.HttpMessageNotReadableException", 
"message": "JSON parse error: Can not construct instance of SearchRequest: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of SearchRequest: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)\n at [Source: [email protected]; line: 2, column: 3]", 
"path": "/acme/request/search" }` 

有谁知道合适的构造和/或注释适用于SearchRequest,以便XML请求正确地反序列化?我在所有getter和setter上都有@JsonProperty(“{Attribute}”),其中{Attribute}是带有初始上限以匹配XML元素名称的属性的名称,以及一个为每个属性值。

TIA, 埃德

+0

你可以分享你的SearchRequest类,你有没有在类中定义的任何参数化构造函数,如果是,那么也添加默认构造函数。 –

+0

寻找JsonMappingExceptions的解决方案,就像https://stackoverflow.com/questions/7625783/jsonmappingexception-no-suitable-constructor-found-for-type-simple-type-class?rq=1,https:// stackoverflow .COM /问题/ 12750681 /不能-构建实例 - 的 - 杰克逊 – tkruse

回答

0

我想通了。我必须向构造函数参数添加注释,例如

public SearchRequest(@JsonProperty("Param1") String param1, 
     @JsonProperty("Param2") String param2) { 
    this.param1 = param1; 
    this.param2 = param2; 
} 

它在那之后正常工作。