Home > OS >  Convert XML to and from Java
Convert XML to and from Java

Time:06-02

I am trying to get the XML response from the rest API. And I am getting JSON response for all customers and XML for single customer from API. PFB the screen print for the case for both cases:

Case 1: When URL= http://localhost:8080/spring-crm-rest/api/customers/ then I am getting JSON response JSON Response

Case 2: When URL = http://localhost:8080/spring-crm-rest/api/customers/1 then I am getting XML response XML Response

Please find below the URL for the complete code to replicate the same at your end. Link for the code: https://drive.google.com/file/d/1fd7DyUsfOvY4fX0nm6j4fzrwxHyg9ZGz/view?usp=sharing

CodePudding user response:

Ok I think the reason why that happens is the following: the path /spring-crm-rest/api/customers/ has return type List<Customer> -> default java List as top level -> json result

while /spring-crm-rest/api/customers/1 has return type Customer as top level which has the javax.xml.bind annotations -> xml result

Changing this may be a bit tricky but these are some possible things you can try:

  1. specifically set the content type of the endpoint like this: @GetMapping(produces = {"application/json"})
  2. removing the @Xml.* annotations -> spring will can serialize the class without any annotations but without them you have less of a control over the resulting json (e.g. renaming fields, etc). Depending on your usecase it might not be needed though
  • Related