【问题标题】:Spring REST: Appropriate constructor for nested XML request body?Spring REST:嵌套 XML 请求正文的适当构造函数?
【发布时间】:2018-06-08 09:58:53
【问题描述】:

我有一个 REST 回调服务,它必须使用以下格式的 XML:

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

实际的 XML 在“Criteria”中有大约 32 个参数,但这给出了基本概念。

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

我的 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: java.io.PushbackInputStream@26bd9717; line: 2, column: 3]",
"path": "/acme/request/search" }`

是否有人知道适用于 SearchRequest 的合适构造函数和/或注释,以便正确反序列化 xml 请求?我在所有 getter 和 setter 上都有 @JsonProperty("{Attribute}") ,其中 {Attribute} 是属性的名称,其初始上限与 XML 元素名称匹配,并且构造函数具有每个属性值的参数.

TIA, 埃德

【问题讨论】:

标签: java xml rest spring-boot jackson


【解决方案1】:

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

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

之后效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 2023-01-08
    • 2015-07-03
    • 2023-04-03
    相关资源
    最近更新 更多