获取 jsonObject 的不存在属性的最佳方法

我尝试通过 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 description

try {

    description = (String) jsonObject.get("description");

} catch (Exception e) {

    description = "";

}


呼如林
浏览 94回答 1
1回答

慕森卡

创建一个custom object并deserialize放入json string该对象的一个实例中。我将在下面展示一个使用gson库的解决方案Maven 依赖<dependency>&nbsp; &nbsp; <groupId>com.google.code.gson</groupId>&nbsp; &nbsp; <artifactId>gson</artifactId>&nbsp; &nbsp; <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&nbsp;public Model(){}然后你可以deserialize the JSON string into the Model class like thisString 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);这样,您就不必每次都分别检查每个参数以将其分配给相应的成员变量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java