使用 JsonPath 使用链接哈希图 java 解析 Json
Parsing Json with linked hashmap java using JsonPath
我有一些 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"
}
}
}
要获取 value
密钥,它将是:
$['MessageAttributes']['eventId']['Value']
或 $.MessageAttributes.eventId.Value
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");
我有一些 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"
}
}
}
要获取 value
密钥,它将是:
$['MessageAttributes']['eventId']['Value']
或 $.MessageAttributes.eventId.Value
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");