简体   繁体   English

Spring FeignClient - 将 RESTful xml 响应视为 JSON

[英]Spring FeignClient - Treat RESTful xml response as JSON

I'm using Spring FeignClient to access a RESTful endpoint, the endpoint returns an xml, I want to get the response as a JSON, which in turn will map to a POJO.我正在使用 Spring FeignClient 访问 RESTful 端点,该端点返回一个 xml,我想以 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); 

In the 'details' object, both ProdId & ProdName are coming as null.在“详细信息”对象中,ProdId 和 ProdName 都为空。 Am I missing anything here?我在这里错过了什么吗? Firstly, Is it possible to get response as JSON instead of XML?首先,是否有可能以 JSON 而不是 XML 的形式获得响应?

If that RESTful service is programmed to return only xml-response, then you cannot ask it to give you json-based response.如果该 RESTful 服务被编程为仅返回 xml-response,则您不能要求它为您提供基于 json 的响应。

But in your case the problem is with class where you want to map the result.但是在您的情况下,问题在于您要映射结果的类。 This xml response actually wraps ProductDetails tag into ns3:Products .这个 xml 响应实际上将ProductDetails标记包装到ns3:Products

So you need to create another class which will hold a reference to ProductDetails object:因此,您需要创建另一个类来保存对ProductDetails对象的引用:

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

Then change the type of getProductDetails method to Product .然后将getProductDetails方法的类型更改为Product

If you still get nulls in your response, then it's probably because of ObjectMapper configuration.如果您的响应中仍然出现空值,则可能是因为 ObjectMapper 配置。 But you can always add @JsonProperty annotation for your fields (in this case it would be @JsonProperty("ProductDetails") for ProductDetails field in Product , and @JsonProperty("ProdId") and @JsonProperty("ProdName") for fields in ProductDetails ).但是您始终可以为您的字段添加@JsonProperty注释(在这种情况下, Product ProductDetails字段为@JsonProperty("ProductDetails") ,而Product字段为@JsonProperty("ProdId")@JsonProperty("ProdName") ProductDetails )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM