2

我正在使用 Spring 5 WebClient 测试功能,并且想提取与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支持下做到这一点?

4

1 回答 1

0

像这样的东西应该可以工作(尝试使用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
于 2018-11-28T18:02:30.390 回答