【问题标题】:@XmlRootElement annotation to read into model@XmlRootElement 注解读入模型
【发布时间】:2018-04-13 07:29:43
【问题描述】:

我正在尝试将 MediaType.APPLICATION_XML 数据读入模型类以使用 Rest API。

示例:代码片段

 @PostMapping(value = "test/{id}/updateSome", consumes = { MediaType.APPLICATION_XML })
 public ResponseEntity<String> updateSome(@PathVariable String id,
                @RequestBody SomeModel reqBody) { ... }

型号:

 @Data
 @XmlRootElement(name = "TYPES")
 class SomeModel {
    private String  x;
    private String  y;
 }

Rest API XML 正文:

<TYPES>
  <TYPE>
     <x>3</x>
     <y>5</y>
  </TYPE>
</TYPES> 

错误:

当@XmlRootElement(name = "TYPES")

(x=null, y=null)

当@XmlRootElement(name = "TYPE")

“状态”:400, "error": "错误请求", “异常”:“org.springframework.http.converter.HttpMessageNotReadableException”, "message": "Could not unmarshal to [class com.model.SomeModel]: 意外元素 (uri:\"\", local:\"TYPES\")。预期元素是 ;嵌套异常是 javax.xml.bind.UnmarshalException: 意外元素(uri:\"\",本地:\"TYPES\")。预期的元素是 ",

【问题讨论】:

    标签: java xml rest spring-boot


    【解决方案1】:

    在您期望的 api 中

    <TYPES>
      <x>..
      <y>...
    

    无法识别附加内容。

    【讨论】:

    • 假设我在一个 中有多个 ,那么我该如何阅读
    • 要做到这一点,您需要一个包含 SomeModel 列表的包装类,请查看此答案以获取 xml 列表stackoverflow.com/questions/28293973/…
    【解决方案2】:

    我想通了。

    创建了两个模型类并使用了@XmlElement 注释。

    模型 1:

     @Data
     @XmlRootElement(name = "TYPES")
     @XmlAccessorType(XmlAccessType.FIELD)
     class SomeModel {
    
        @XmlElement(name = "TYPE")
        private SomeOtherModel[] type;
    
     }
    

    模型 2:

     @Data
     @XmlRootElement(name = "TYPE")
     @XmlAccessorType(XmlAccessType.FIELD)
     class SomeOtherModel {
    
         private String  x;
         private String  y;
    
     }
    

    按预期获得值 (x=3, y=5)

    【讨论】:

      猜你喜欢
      • 2013-05-11
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2016-08-31
      相关资源
      最近更新 更多