[英]How to parse this json with multiple objects
開發人員我被困在解析這種 JSON 我不明白如何獲得狀態和消息的價值,任何幫助都會非常明顯。 我得到錯誤的值,但是當我想訪問狀態和消息的值時,它會拋出錯誤 JSON 格式:
{ "error": { "status": 400, "message": "Wrong number of segments" } }
我用於解析 json 的代碼:
try { JSONObject jso = new JSONObject(String.valueOf(response)); //jso.getJSONObject("error").getJSONObject("message"); jso.getJSONObject("error"); jso.getJSONObject("status").toString(200); Log.d(TAG,"jso1"+jso); } catch (JSONException e) { e.printStackTrace(); }
try {
JSONObject jso = new JSONObject(String.valueOf(response));
//jso.getJSONObject("error").getString("message");
jso.getJSONObject("error");
jso.getJSONObject("error").getInt("status"); // if it was string use getString or it was int than use value getInt
Log.d(TAG,"jso1"+jso);
} catch (JSONException e) {
e.printStackTrace();
}
嘗試這個
try {
JSONObject fullResponse = new SONObject(String.valueOf(response));
JSONObject errorData = fullResponse.getJSONObject("error");
String errorCode = errorData.getObject("status");
String errorMessage = errorData.getString("message");
Log.d(TAG,"Result = "+errorCode +" - "+errorMessage );
} catch (JSONException e) {
e.printStackTrace();
}
JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(String.valueOf(response));
上面的命令會給你 JSON 的響應。
要獲取狀態和消息,您需要將錯誤提取為單獨的 JSONObject,然后解析狀態和消息
JSONObject errorObj = (JSONObject) jso.get("error");
String message = errorObj.get("message").toString();
int status = Integer.parseInt(errorObj.get("status").toString());
請記住使用層次結構進行解析和檢索。因此,如果狀態和消息在“錯誤”內,則將錯誤提取為 JSONObject,然后檢索子鍵。 作為一個好的做法,檢查密鑰是否存在:-
if(errorObj.has("")) {
// do something
}
添加工作樣本:-
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
private static void parseJsonTest() {
String json = "{\n" +
" \"error\": {\n" +
" \"status\": 400,\n" +
" \"message\": \"Wrong number of segments\"\n" +
" }\n" +
"}";
try {
JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(json);
JSONObject errorObj = (JSONObject) jso.get("error");
String message = errorObj.get("message").toString();
int status = Integer.parseInt(errorObj.get("status").toString());
System.out.println(message + " >>>>>>> " + status);
} catch (Exception e) {
}
}
Output:-
Wrong number of segments >>>>>>> 400
將 Json 轉換為 java 的最佳方法是使用轉換器庫,例如 Gson 檢查以下鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.