首页 > 解决方案 > 使用 JsonPath 使用链接的 hashmap java 解析 Json

问题描述

我有一些包含链接哈希图的 json 我可以像这样使用 gson 获取我想要的元素

Gson gson = new GsonBuilder().create()

JsonObject job = gson.fromJson(message.getBody(), JsonObject.class)
JsonElement entry=job.getAsJsonObject("MessageAttributes").getAsJsonObject("eventId").get("Value")

我想使用类似这样的 JsonPath

JsonObject j = JsonPath.read(awsBody, "$['MessageAttributes']")
j.getAsJsonObject("eventId").get("Value")

虽然这给了我错误No such instance method: 'com.google.gson.JsonObject java.util.LinkedHashMap.getAsJsonObject (java.lang.String)'

这是我的json

{
    "MessageId": "8342fb55-9db8-42cb-8f59-c6abc8039b72",
    "Type": "Notification",
    "Timestamp": "2020-04-15T14:40:06.927960Z",
    "Message": "Some message here ",
    "TopicArn": "arn:aws:sns:us-east-1:000000000000:quote-event",
    "MessageAttributes": {
        "eventId": {
            "Type": "String",
            "Value": "HELLO-WORLDaaa-4bb04d9e-2522-4918-98c9-5a88094d3a3a"
        }
    }
}

标签: javajsonparsinggson

解决方案


要获得value密钥,它将是:

$['MessageAttributes']['eventId']['Value']或者$.MessageAttributes.eventId.Value

对于测试和实验,请使用此站点。另外,使用这个来阅读 jsonPath 的规范。


推荐阅读