Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

java - How to deal with API call that can return different JSON data structure depending on result data

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...