Home > Software design >  Using RestTemplate to get a list of XML objects
Using RestTemplate to get a list of XML objects

Time:11-16

I'm wondering how, calling an external API service to get a list of object mapped by my class.

This is what the XML looks like

<ArrayOfObject>
    <Object>
        <id></id>
        <name></name>
        <var1></var1>
        <var2></var2>
        <var3></var3>
    </Object>
    <Object>
       <id></id>
       <name></name>
       <var1></var1>
       <var2></var2>
       <var3></var3>
   </Object>
  
   ...

</ArrayOfObject>

I'm trying to get only the id and name so i've tried to map in my class only theese two fields (tried even with all of them but didn't work, not expecting that):

public class Object{
    public String id, name;
    
    public Object() {}
    public Object(String id, String name) {
        this.id = id;
        this.name= name;
    }


    public String getId() {return id;}
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {return name;}
    public void setName(String name) {
        this.name = name;
    }

and wrap it into


public class ArrayOfObject {
    
    private List<Object> objects;
    
    public ArrayOfObject () {
        object = new ArrayList<>();
    }

    
    public List<Object> getObjects() {return objects;}
    public void setObjects(List<Object> objects) {
    this.objects = objects;
    }   
}

So now this is what my controller looks like

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping
public class RestCall {

    @GetMapping("/objects")
    public List<Object> getObject(){
        final String uri = "";
        
    RestTemplate rt = new RestTemplate();
        
    ArrayOfObject result = rt.getForObject(uri, ArrayOfObject.class);
    return result.getObjects();
    }
}

When it comes time to test the results are:

org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class it.me.model.ArrayOfObject] and content type [text/xml;charset=utf-8]

Did i do something wrong or am i missing something?

CodePudding user response:

I suppose you're using Jackson for (de)serialization... Did you add jackson xml module?

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

And add @JsonIgnoreProperties to your pojo to omit unmapped fields

@JsonIgnoreProperties
public class Object{

For deserializing to list try...

@JacksonXmlElementWrapper(useWrapping = false)
private List<Object> object; // same name as in xml

https://www.baeldung.com/jackson-xml-serialization-and-deserialization

  • Related