我遇到的情况是,有时 API 的响应是
{
"SuccessCode": "OPERATION_SUCCESS",
"Message": "Operation completed successfully"
}
有时,响应是
{
"FaultId": "User already exists",
"fault": "FAULT_USER_ALREADY_EXISTS"
}
如何以通用方式反序列化它以满足不同的响应?
您可以创建两个不同的对象来表示错误和成功的响应:
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 ...
}
然后,假设成功的响应具有 http 状态代码 200,否则这是一个错误,您可以:
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);
}