[英]How to parse json response with array list
我有一個下面的響應,由於響應是從JSON
對象0開始的,所以我無法驗證。這意味着如果一個以上的對象,響應將從0開始到您擁有的對象數。
我已經嘗試過了,但是它不起作用,最終導致堆棧溢出錯誤。
public static void Location_ContactValidation(Response response, String code, String message, ExtentTest log) {
try {
softAssert = new SoftAssert();
org.json.JSONObject jsonObject = new org.json.JSONObject(response);
org.json.JSONObject getSth = jsonObject.getJSONObject("status");
status_Message = getSth.get("message");
softAssert.assertEquals(code, code);
softAssert.assertEquals(message, status_Message);
log.log(LogStatus.INFO, "Validation: The status code is " + code);
log.log(LogStatus.INFO, "Validation: The status message is " + status_Message.toString());
} catch (Exception e) {
log.log(LogStatus.INFO, "Validation: The status code is " + code);
if (status_Message != null) {
log.log(LogStatus.INFO, "Validation: The status message is " + status_Message.toString());
}
System.out.println(e.getMessage());
if (softAssert != null) {
softAssert.assertAll();
}
}
}
流的堆棧溢出錯誤-
java.lang.StackOverflowError
at org.json.JSONObject.wrap(JSONObject.java:1746)
at org.json.JSONArray.<init>(JSONArray.java:176)
at org.json.JSONObject.wrap(JSONObject.java:1747)
at org.json.JSONObject.populateMap(JSONObject.java:1167)
這是我想解析的回復
{
"0": {
"status": "OK",
"data": {
"id": "*************",
"mobile": "*************"
},
"message": "Submitted Successfully"
},
"status": "OK"
}
我需要驗證手機號碼,包括狀態和消息。 但是無法做到。 如果通過請求再發送一個數字,則響應會增加,首先創建數組,如0
所示,然后是1
。
我感謝您的幫助。
您可以使用keySet
方法列出給定JSONObject
所有鍵。 之后,您可以直接挖掘必填字段。
以下代碼顯示了如何讀取所有必填字段:
import org.json.JSONObject;
import java.io.File;
import java.nio.file.Files;
public class OrgJsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
String json = String.join("", Files.readAllLines(jsonFile.toPath()));
JSONObject response = new JSONObject(json);
response.keySet().forEach(key -> {
JSONObject object = response.optJSONObject(key);
// if given key represents object it must be data
if (object != null) {
final String dataKey = "data";
JSONObject data = object.optJSONObject(dataKey);
// extract mobile from data and remove data
// this way JSON node is much simpler
if (data != null) {
final String mobileKey = "mobile";
String mobile = data.optString(mobileKey);
System.out.println("Mobile => " + mobile);
}
System.out.println("status => " + object.optString("status"));
System.out.println("message => " + object.optString("message"));
}
});
}
}
對於以下JSON
有效負載:
{
"0": {
"status": "OK",
"data": {
"id": "1",
"mobile": "44-32-12"
},
"message": "Submitted Successfully"
},
"1": {
"status": "OK",
"data": {
"id": "2",
"mobile": "9981234-543"
},
"message": "Submitted Successfully"
},
"status": "OK"
}
打印:
Mobile => 44-32-12
status => OK
message => Submitted Successfully
Mobile => 9981234-543
status => OK
message => Submitted Successfully
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.