如何使用 Spring WebClient 按名称获取 json 字段?
How to get a json field by name using Spring WebClient?
我有以下 JSON 响应:
{
"Count": 1,
"Products": [
{
"ProductID": 3423
},
{
"ProductID": 4321
}
]
}
我希望能够使用 WebClient 从 Products 数组中 return "Product" 的列表,而不必使用字段 'ArrayList products' 创建单独的 Dto class
我用过类似的东西
webClient.get()
.uri(uriBuilder -> uriBuilder
.path(URI_PRODUCTS)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Product.class)
.collectList();
它检索到一个包含一个产品但所有值为空的列表。我能够让它与 DTO 响应一起工作,例如
...retrieve().bodyToMono(ProductResponse.class).block();
其中 ProductResponse 中包含产品列表。但我试图避免创建额外的 class。有没有类似使用jsonPath(类似于WebTestClient)拉取字段的方法?
在 retrieve()
之后,您总是可以 .map
您的结果到相应的类型。在 JsonNode
path()
实例方法的帮助下,您可以类似于 WebTestClient
jsonPath()
webClient.get()
.uri(uriBuilder -> uriBuilder
.path(URI_PRODUCTS)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(JsonNode.class)
.map(s-> s.path("Products"))
.map(s->{
try {
return mapper.readValue(s.traverse(), new TypeReference<List<Product>>() {} );
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<Product>();
}
})
.block();
我有以下 JSON 响应:
{
"Count": 1,
"Products": [
{
"ProductID": 3423
},
{
"ProductID": 4321
}
]
}
我希望能够使用 WebClient 从 Products 数组中 return "Product" 的列表,而不必使用字段 'ArrayList products' 创建单独的 Dto class
我用过类似的东西
webClient.get()
.uri(uriBuilder -> uriBuilder
.path(URI_PRODUCTS)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToFlux(Product.class)
.collectList();
它检索到一个包含一个产品但所有值为空的列表。我能够让它与 DTO 响应一起工作,例如
...retrieve().bodyToMono(ProductResponse.class).block();
其中 ProductResponse 中包含产品列表。但我试图避免创建额外的 class。有没有类似使用jsonPath(类似于WebTestClient)拉取字段的方法?
在 retrieve()
之后,您总是可以 .map
您的结果到相应的类型。在 JsonNode
path()
实例方法的帮助下,您可以类似于 WebTestClient
jsonPath()
webClient.get()
.uri(uriBuilder -> uriBuilder
.path(URI_PRODUCTS)
.build())
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(JsonNode.class)
.map(s-> s.path("Products"))
.map(s->{
try {
return mapper.readValue(s.traverse(), new TypeReference<List<Product>>() {} );
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<Product>();
}
})
.block();