Flopn
Flopn

Reputation: 195

Spring REST fetch list of objects from

I'm trying to implement a client using Spring Boot which will fetch all products from a site and store them in a database. The storing part is taken care of, but I'm having trouble fetching a list of all the products. When testing with Postman, I can get a response with a body like this:

<Response>
    <Products>
        <Product Id="221">
            <Name>Screwdriver<Name>
            <Price>5,99</Price>
            <Currency>USD<Currency>
        </Product>
        ...
   </Products>
</Response>

I have a Products class with all the fields, getters and setters. Here's what works and outputs the raw body xml:

@Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {

        return args -> {
            ResponseEntity<String> response = restTemplate.getForEntity(resourceUrl, String.class);
            log.info(response.toString());
        };

    }

However, I can't seem to get it to fetch all of the individual products from the body. Would I be best off using the body fetched here and mapping them to individual Objects, or is there a direct way to do this from the restTemplate?

Any help at all would be appreciated.

Upvotes: 0

Views: 326

Answers (1)

so-random-dude
so-random-dude

Reputation: 16465

As far as I understood, you are looking for a way to deserialize your xml string to Java Objects. You have many different options to do it

  1. Use JAXB (My personal favorite because of low maintenance), XStream or JibX library and let that take care of the conversion for you . For this you might need to add certain annotations to your Product class (In case of JAXB, you can auto-generate this, if you have access to the XSD).
  2. Go the painful route- use any of the parsers (depending on your use case) DOM, SAX or StaX parser and create Product instances on your own.

Upvotes: 1

Related Questions