0

Hi I am hitting an endpoint with rest template and getting the response.
When I use String as return type and print the response it's an XML response with multiple tags.
and when I use Object as return type then RestTemplate is mapping only last tag from the list.

With String.class as return type
Request:

ResponseEntity<String> response = restTemplate.postForEntity(urlTemplate, httpEntity, String.class);
System.out.println(response.getBody());

Response:

<Order>
    <OrderLines>
        <OrderLine LineID="1"></OrderLine>
        <OrderLine LineID="2"></OrderLine>
        <OrderLine LineID="3"></OrderLine>
    </OrderLines>
</Order>

With Object.class as return type
Request:

ResponseEntity<Object> response = restTemplate.postForEntity(urlTemplate, httpEntity, Object.class);

System.out.println(response.getBody());

Response:

{
    "OrderLines": {
        "OrderLine": {
            "LineID": "3"
        }
    }
}

Expected Response with Object.class as return type is:

{
    "OrderLines": {
        "OrderLine": [
            {
                "LineID": "1"
            },
            {
                "LineID": "2"
            },
            {
                "LineID": "3"
            }
        ]
    }
}

Please suggest the solution to this.

Onkar Patil
  • 80
  • 2
  • 11

1 Answers1

0

You can create a model class to Map the expected Response with Object.class as return type, But instant you will need to have it like OrderLines.class ( which is your newly created model )

Then you can use ObjectMapper or Gson to map the response like the following.

OrderLines obj = gson.fromJson(stringResponse, OrderLines.class); 
return obj;

This will have the created model object to be returned after getting the information needed from the string returned type.

George
  • 2,292
  • 2
  • 10
  • 21