gpt4 book ai didi

java - 确保休息 : Deserialization and Inheritance to cater to varied Responses being returned by an API endpoint

转载 作者:行者123 更新时间:2023-12-01 18:41:27 35 4
gpt4 key购买 nike

我遇到的情况是,有时 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);
}

关于java - 确保休息 : Deserialization and Inheritance to cater to varied Responses being returned by an API endpoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925396/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com