import org.json.JSONObject;
import org.json.JSONArray;
String response = prev.getResponseDataAsString();
try {
// 将响应字符串转换为JSON对象
JSONObject jsonResponse = new JSONObject(response);
// 获取 code, message 和 skuList 字段
int code = jsonResponse.getInt("code");
String message = jsonResponse.getString("message");
JSONArray skuList = jsonResponse.getJSONObject("data").getJSONArray("skuList");
// 检查 code 是否为 1 和 message 是否为 "success"
if (code != 1) {
prev.setSuccessful(false);
prev.setResponseMessage("Invalid code, expected 1 but got " + code);
} else if (!"success".equals(message)) {
prev.setSuccessful(false);
prev.setResponseMessage("Invalid message, expected 'success' but got " + message);
} else if (skuList == null || skuList.length() == 0) {
// 检查 skuList 是否为空
prev.setSuccessful(false);
prev.setResponseMessage("skuList is empty or null");
} else {
// 如果没有失败,则断言通过
prev.setSuccessful(true);
}
} catch (Exception e) {
// 捕获JSON解析异常
prev.setSuccessful(false);
prev.setResponseMessage("Error parsing the response: " + e.getMessage());
}
2、响应demo:
{
"code": 1,
"data": {
"skuList": [
{
"quantity": 2,
"salePrice": 28.99,
"discountPrice": 28.99,
"skuId": "529874918398763056"
},
{
"quantity": 2,
"salePrice": 28.99,
"discountPrice": 28.99,
"skuId": "529874918398763050"
}
]
},
"message": "success"
}