java - 在 Java 中使用链式键获取嵌套 JSON 值

标签 java json

我有一个如下所示的 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/

相关文章:

java - 没有这样的表 : goods:

python - Google App Engine NDB 数据库损坏了吗?

php - 使用 PHP 在 Mysql 中数组到字符串错误

java - 我们可以在已经运行的 Kubernetes pod 中运行一个可执行的 jar 文件吗?

javascript - 为什么 p :inputTextArea value is not set?

php连接多个json文件并按id分组

json - 在 Go 中解析 JSON 'NaN' 值

arrays - 如何将非标准索引的数组转换为json?

java - 如何在android中创建三角形

java - 未找到 HTTP 请求与 URI 的映射