I am trying to write code using RestTemplate exchange to query an API that returns song info. The problem is that the data looks like this when data is found but
{"search":[{"song_id":"4R9o2J","song_title":"xxxx", ...}]
but like this if the song is not found
{"search":{"error":"no result"}}
When reading valid data my result object looks like this
Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SongSearch {
List<SongInfo> search;
}
The problem is that when the data is valid, there is no property to contain the array of info... it is the contents of the "search": [{....}] so I can't create a property that will get ignored when it is not found even though the not found message has an error property. In other words, the search property can contain an array OR a single property depending on whether data was found or not.
My exchange call looks like this:
ResponseEntity<SongSearch> res = restTemplate.exchange(url, HttpMethod.GET, entity, SongSearch.class);
I've been able to write code that catches the deserialization exception in the not found case but the exception does not contain the actual error message from the API, which I'd want to return. I am currently able to hack it by making a call again with a different object to capture the error but that seems insane. There MUST BE a better way to do this. Just to be clear, this is not an actual error status returned from the client... the data is just different but it breaks the deserialization.
Anyone have suggestions?
question from:
https://stackoverflow.com/questions/65947133/how-to-deal-with-api-call-that-can-return-different-json-data-structure-dependin 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…