super.t
super.t

Reputation: 2736

Spring RestTemplate dynamic JSON property name

I need to consume an API which returns pages of objects using Spring RestTemplate. The problem is that the name of the JSON page property which holds the collection of objects is dynamic. How can I map this dynamic JSON prop to its static counterpart in my POJO?

Here's the pojo:

public class DTO<T> {
    private List<T> items;

    public List<T> getItems() {
        return items;
    }

    public DTO<T> setItems(List<T> items) {
        this.items = items;
        return this;
    }
}

Here's two examples of JSON:

{
    "forms": [{},{},{}]
}

{
    "submissions": [{},{},{}]
}

In the former case I need to map JSON forms onto POJO's items, in the latter - submissions onto items. How do I go about that?

Upvotes: 0

Views: 579

Answers (2)

super.t
super.t

Reputation: 2736

I've just aliased the JSON field whose name can vary:

public class DTO<T> {
    private Integer prettyFieldId;
    private Integer pages;
    private Integer total;

    @JsonAlias({"forms", "submissions"})
    private List<T> items;

    //getters, setters
}

Upvotes: 0

Oğuzhan Ayg&#252;n
Oğuzhan Ayg&#252;n

Reputation: 137

try using maps like bellow

public class DTO<T> {
private Map<String,List<T>> items;

public Map<String,List<T>> getItems() {
    return items;
}

public DTO<T> setItems(Map<String,List<T>> items) {
    this.items = items;
    return this;
}
}

Upvotes: 2

Related Questions