使用JsonPath解析带有链接hashmap java的Json



我有一些json,其中包含一个链接的hashmap,我可以使用类似的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"
}
}
}

要获得value密钥,需要:

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

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

JsonPath不能直接与GSON对象一起工作,因为它在内部使用net.minidev.json库,因此需要首先配置JsonPath
  • []用于基于索引、范围或条件的选择,因此要访问MessageAttributes对象,请使用$.MessageAttributes路径。

  • GSON创建一个配置对象作为

    Configuration config = Configuration
    .builder()
    .jsonProvider(new GsonJsonProvider())
    .mappingProvider(new GsonMappingProvider())
    .build();
    

    现在,在读取对象时使用配置为:

    JsonObject j = JsonPath.using(config).parse(awsBody)
    .read("$.MessageAttributes"); // path for MessageAttributes, is an elemnt from root
    String value = j.getAsJsonObject("eventId").get("Value");
    

    最新更新