我有一个如下所示的 JSON 对象。在 Java 中是否可以使用链式键从一次 get 调用中获取嵌套值?例如:
String fname = jsonObj.get("shipmentlocation.personName.first")
{
"shipmentLocation": {
"personName": {
"first": “firstName”,
"generationalSuffix": "string",
"last": "string",
"middle": "string",
"preferredFirst": "string",
"prefix": "string",
"professionalSuffixes": [
"string"
]
}
},
"trackingNumber": "string"
}
这对我使用 JSONObject 类不起作用,所以我很好奇是否有其他方法可以做到这一点。谢谢!
最佳答案
根据您提供的 json,您需要经历几个级别。
String firstName = jsonObj.getJSONObject("shipmentLocation").getJSONObject("personName").getString("first");
请注意,如果您在 json 节点或其子节点中查找的任何字段可能不存在,则可能会遇到上述问题。在这种情况下,明智的做法是查看 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
}
关于java - 在 Java 中使用链式键获取嵌套 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992973/