'REST Assured: Deserialization and Inheritance to cater to varied Responses being returned by an API endpoint
I have a situation where sometimes the response of an API is
{
"SuccessCode": "OPERATION_SUCCESS",
"Message": "Operation completed successfully"
}
and at times, the response is
{
"FaultId": "User already exists",
"fault": "FAULT_USER_ALREADY_EXISTS"
}
How do I deserialize this in a generic way which caters to the varied responses?
Solution 1:[1]
You can create two different objects that will denote the faulty and successful responses:
public class Successful {
private String SuccessCode; // or successCode as usually done in java + annotation to map the json field
private String Message;
... getters, setters ...
}
public class Faulty {
private String FaultId;
private String fault;
... getters, setters ...
}
Then, assuming, that successful responses have http status code 200, and otherwise its a fault, you can:
Response resp = when().get(<SOME_URL_GOES_HERE);
if(resp.getStatusCode () == 200) {
Successful respSuccess = resp.body().as(Successful.class);
} else {
Faulty faulty = resp.body().as(Faulty.class);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mark Bramnik |