亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取 jsonObject 的不存在屬性的最佳方法

獲取 jsonObject 的不存在屬性的最佳方法

呼如林 2023-03-23 13:49:28
我嘗試通過 REST API 從 JIRA 收集數據。我可以獲得帶有 JSONObjects 的 jsonArray。這些 JSONObjects 可能包含屬性 a;b;c;d。一些 JSONObjects 可能只包含例如 a;b;c 缺少屬性 d。我試圖在代碼中收集這些屬性。由于某些 JSONObjects 缺少某些屬性,我可能會收到這樣的錯誤消息:Exception in thread "main" org.json.JSONException: JSONObject["d"] not found.我使用了 try/catch 方法(見下文),因此我通過忽略它來避免錯誤消息。有沒有更好的方法來解決這樣的問題?JsonNode jsonNode = response.getBody();JSONArray jsonArray = jsonNode.getArray();for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);String name = (String) jsonObject.get("name");String startDate = (String) jsonObject.get("startDate");String releaseDate = (String) jsonObject.get("releaseDate");Integer projectId = (Integer) jsonObject.get("projectId");String description;// getting the error for the attribute descriptiontry {    description = (String) jsonObject.get("description");} catch (Exception e) {    description = "";}
查看完整描述

1 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

創建一個custom object并deserialize放入json string該對象的一個實例中。我將在下面展示一個使用gson庫的解決方案


Maven 依賴


<dependency>

    <groupId>com.google.code.gson</groupId>

    <artifactId>gson</artifactId>

    <version>2.8.5</version>

</dependency>

模型類


public class Model {


private boolean archived;

private String releaseDate;

private String name;

private String self;

private String userReleaseDate;

private long id;

private long projectId;

private boolean released;


//getters && setters ommitted 


public Model(){


}

然后你可以deserialize the JSON string into the Model class like this


String json = "{\"archived\":false,\"releaseDate\":\"2019-07-16\",\"name\":\"test 1.0\",\"self\":\"https://test/rest/api/latest/test/10000\",\"userReleaseDate\":\"16/Jul/19\",\"id\":\"10000\",\"projectId\":10000,\"released\":true}";

Gson gson = new GsonBuilder().create();

Model model = gson.fromJson(json, Model.class);

這樣,您就不必每次都分別檢查每個參數以將其分配給相應的成員變量。


查看完整回答
反對 回復 2023-03-23
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號