【问题标题】:Spring WebClient extract JsonPath valueSpring WebClient 提取 JsonPath 值
【发布时间】:2018-08-01 23:28:38
【问题描述】:

我正在使用 Spring 5 WebClient test features 并想提取与 jsonPath 表达式匹配的正文,但找不到任何合适的方法。例如(代码在 Kotlin 中,但我希望这没有任何区别):

client!!.get().uri("/app/metrics")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .exchange()
                .expectStatus().isOk
                .expectBody()
                .jsonPath("$.names")
                .isArray

实际的json体是:

{
"names": [
"jvm.buffer.memory.used",
"jvm.memory.used",
"jvm.buffer.count",
"jvm.gc.memory.allocated",
"logback.events",
"process.uptime",
"jvm.memory.committed",
"system.load.average.1m",
"jvm.gc.max.data.size",
"jvm.buffer.total.capacity",
"jvm.memory.max",
"system.cpu.count",
"jvm.threads.daemon",
"system.cpu.usage",
"jvm.threads.live",
"process.start.time",
"jvm.threads.peak",
"jvm.gc.live.data.size",
"jvm.gc.memory.promoted",
"process.cpu.usage"
]
}

所以我想将名称列表放入列表变量并使用它。有没有办法在当前的jsonPath 支持下做到这一点?

【问题讨论】:

    标签: spring spring-test spring-webflux spring-kotlin


    【解决方案1】:

    这样的事情应该可以工作(尝试springBootVersion = '2.1.0.RELEASE'):

    client.get().uri("/app/metrics")
        .accept(MediaType.APPLICATION_JSON_UTF8)
        .exchange()
        .expectStatus().isOk
        .expectBody()
        .jsonPath("$.names")
        .value<JSONArray> { json ->
            json.toList().forEach { println(it) }
        }
    

    将打印:

    jvm.buffer.memory.used
    jvm.memory.used
    jvm.buffer.count
    jvm.gc.memory.allocated
    logback.events
    process.uptime
    jvm.memory.committed
    system.load.average.1m
    jvm.gc.max.data.size
    jvm.buffer.total.capacity
    jvm.memory.max
    system.cpu.count
    jvm.threads.daemon
    system.cpu.usage
    jvm.threads.live
    process.start.time
    jvm.threads.peak
    jvm.gc.live.data.size
    jvm.gc.memory.promoted
    process.cpu.usage
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 2022-11-09
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2017-04-23
      相关资源
      最近更新 更多