简体   繁体   中英

Jackson deserialization bellow JSON property

I want to fetchMultiple(ParameterizedTypeReference<List<T>> responseType) for a given List<T> , in this case, I want to get directly a List<Account> but I am getting an error because the list of accounts is encapsulated in another object, as shown below:

{
    "accounts": [
        {
            "accountUid": "c75deb59-5d52-4a23-af7b-fce29927ce9d",
            "defaultCategory": "b4189da5-7688-42d0-86e3-14ae9031e01d",
            "currency": "GBP",
            "createdAt": "2020-08-05T16:50:50.536Z"
        }
    ]
}

There is some Jackson annotation to filter this somehow in order to be processed like this:

[
    {
        "accountUid": "c75deb59-5d52-4a23-af7b-fce29927ce9d",
        "defaultCategory": "b4189da5-7688-42d0-86e3-14ae9031e01d",
        "currency": "GBP",
        "createdAt": "2020-08-05T16:50:50.536Z"
    }
]

POJO

@Data
public class Account {

    private String accountUid;
    private String defaultCategory;
    private String currency;
    private String createdAt;

}

RestRequestTemplate.java

public List<T> fetchMultiple(ParameterizedTypeReference<List<T>> responseType) {
        return new RestTemplate().exchange(this.url, this.httpMethod, this.request, responseType).getBody();
}

AccountsServiceImpl.java

public List<Account> getAccounts() {
   RestRequestTemplate restRequestTemplate = new RestRequestTemplate(GET_ACCOUNTS, HttpMethod.GET, Collections.EMPTY_MAP);
   return restRequestTemplate.fetchMultiple(new ParameterizedTypeReference<List<Account>>() {});
}

There is indeed an annotation to ignore the root object. It is called @JsonUnwrapped . Annotate your method with that annotation and your json should be without the root object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM