【问题标题】:Parsing Json with linked hashmap java using JsonPath使用 JsonPath 使用链接的 hashmap java 解析 Json
【发布时间】:2020-04-15 15:12:18
【问题描述】:

我有一些包含链接哈希图的 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"
        }
    }
}

【问题讨论】:

    标签: java json parsing gson


    【解决方案1】:

    要获得value 密钥,它将是:

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

    对于测试和实验,请使用this site。另外,请使用this one 阅读jsonPath 的规范。

    【讨论】:

    • 这正是我想要的
    【解决方案2】:
    1. JsonPath 不能直接与 GSON 对象一起使用,因为它在内部使用 net.minidev.json 库,因此需要先配置 JsonPath

    2. [] 用于索引、范围或基于条件的选择,因此要访问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");
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 1970-01-01
      • 2022-01-03
      • 2017-02-05
      • 1970-01-01
      • 2021-09-18
      • 2023-02-23
      • 2016-02-05
      • 1970-01-01
      相关资源
      最近更新 更多