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.
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. Am I missing anything here? Firstly, Is it possible to get response as JSON instead of XML?
If that RESTful service is programmed to return only xml-response, then you cannot ask it to give you json-based response.
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
.
So you need to create another class which will hold a reference to ProductDetails
object:
public class Product { //class name can be anything
private ProductDetails ProductDetails;
//getters, setters
}
Then change the type of getProductDetails
method to Product
.
If you still get nulls in your response, then it's probably because of ObjectMapper configuration. 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
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.