2 回答

TA貢獻1906條經(jīng)驗 獲得超3個贊
使用您提供的json,您需要經(jīng)歷幾個層次。
String firstName = jsonObj.getJSONObject("shipmentLocation").getJSONObject("personName").getString("first");
請注意,如果您在json節(jié)點或其子節(jié)點中查找的任何字段都可能不存在,則上述內(nèi)容可能會遇到一些空指針問題。在這種情況下,明智的做法是要么看一下java,要么Optional在每個步驟都使用null檢查,如下所示:
String firstName = null;
JSONObject shipmentLocation = jsonObj.getJSONObject("shipmentLocation");
if (shipmentLocation != null) {
JSONObject personName = shipmentLocation.getJSONObject("personName");
if (personName != null) {
firstName = personName.getString("first");
}
}
if (firstName != null) {
// do something with the first name
}
添加回答
舉報