简体   繁体   中英

Parsing Json with linked hashmap java using JsonPath

I have some json that contains a linked hashmap I can get the element I want using gson like this

Gson gson = new GsonBuilder().create()

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

I want to use JsonPath something like this

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

although this gives me the error No such instance method: 'com.google.gson.JsonObject java.util.LinkedHashMap.getAsJsonObject (java.lang.String)'

Here is my 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"
        }
    }
}

To get the value key it would be:

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

For testing and experimentation use this site . Also, use this one to read jsonPath's specification.

  1. JsonPath doesn't work with GSON object directly as it uses net.minidev.json library internally so JsonPath needs to be configured first

  2. [] is used for indexes, range or condition-based selection so to access the MessageAttributes object, use $.MessageAttributes path.

Create a configuration object for GSON as

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

Now use the configuration while reading the object as:

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

String value = j.getAsJsonObject("eventId").get("Value");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM