【问题标题】:Spring FeignClient - Treat RESTful xml response as JSONSpring FeignClient - 将 RESTful xml 响应视为 JSON
【发布时间】:2020-02-25 05:01:28
【问题描述】:

我正在使用 Spring FeignClient 访问一个 RESTful 端点,该端点返回一个 xml, 我想以 JSON 形式获取响应,而 JSON 又将映射到 POJO。

1) When I access the endpoint on the browser, I get response as below, 
<ns3:Products xmlns:ns2="http://schemas.com/rest/core/v1" xmlns:ns3="http://schemas/prod/v1">
<ProductDetails>
<ProdId>1234</ProdId>
<ProdName>Some Text</ProdName>
</ProductDetails>
</ns3:Products>


2) @FeignClient(value = "productApi", url = "http://prodservice/resources/prod/v1")
public interface ProductApi {

   @GetMapping(value="/products/{productId}", produces = "application/json")
   ProductDetails getProductDetails(@PathVariable("productId") String productId) 

    // where, /products/{productId} refers the RESTful endpoint 
    // by mentioning, produces = "application/json", I believe the response xml would be converted to JSON Java POJO. 


3) POJO
public class ProductDetails {
private String ProdId;
private String ProdName;

//...setters & getters 
} 

4) Service Layer 
ProductDetails details = productApi.getProductDetails(productId); 

在“详细信息”对象中,ProdId 和 ProdName 都为 null。 我在这里错过了什么吗?首先,是否可以获得 JSON 而不是 XML 的响应?

【问题讨论】:

  • 您可以将xml转换为json。

标签: java spring feign


【解决方案1】:

如果那个 RESTful 服务被编程为只返回 xml 响应,那么你不能要求它给你基于 json 的响应。

但在您的情况下,问题在于您要映射结果的类。 这个 xml 响应实际上将 ProductDetails 标记包装到 ns3:Products 中。

所以你需要创建另一个类来保存对ProductDetails 对象的引用:

public class Product {   //class name can be anything 
    private ProductDetails ProductDetails;
    //getters, setters
}

然后将getProductDetails方法的类型改为Product

如果您的响应中仍然出现空值,则可能是因为 ObjectMapper 配置。但是您始终可以为您的字段添加 @JsonProperty 注释(在 在这种情况下,对于 Product 中的 ProductDetails 字段将是 @JsonProperty("ProductDetails"),对于 ProductDetails 中的字段将是 @JsonProperty("ProdId")@JsonProperty("ProdName")

【讨论】:

  • 什么是Category?你还没有告诉我们这门课。也许您可以尝试通过执行类似步骤进一步解决问题?
  • 请查看更新。为了更好地理解,我用自己的名称替换原始名称,添加了一个包装类并包含@JsonProperty 注释,现在出现一些错误,'feign.codec.DecodeException: Error while extracting response for type [class com.model.Product] and content类型[应用程序/json];嵌套异常是 '...HttpMessageNotReadableException:JSON 解析错误:无法从 START_ARRAY 令牌中反序列化 com.model.ProductDetails 的实例;嵌套异常是'....MismatchedInputException:无法反序列化com.model.ProductDetails 的实例超出START_ARRAY ...'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 2016-11-13
  • 2011-09-21
  • 1970-01-01
  • 2017-07-15
  • 2018-06-02
  • 2013-09-26
相关资源
最近更新 更多