gpt4 book ai didi

java - 从 Rest API 返回带有值的键

转载 作者:行者123 更新时间:2023-11-29 04:11:56 24 4
gpt4 key购买 nike

我想从 Rest API 端点返回 JSON 作为带有值的键。示例:

  {
"terminal 1":
{"date":"2018-10-06T00:00:00.000+0000","volume":111,"count":1},
"terminal 2":
{"date":"2018-11-06T00:00:00.000+0000","volume":122,"count":1}
}

如何添加 key ?我想应该是这样的:

List<String<List<TopTerminalsDTO>>>>

你能给我一些代码示例吗?

清理最终代码的最新尝试:

@GetMapping("/terminals")
public ResponseEntity<Map<Integer, List<TopTerminalsDTO>>> getTopTerminalsVolumes(
@RequestParam(value = "start_date", required = true) String start_date,
@RequestParam(value = "end_date", required = true) String end_date) {

LocalDateTime start_datel = LocalDateTime.now(Clock.systemUTC());
LocalDateTime end_datel = LocalDateTime.now(Clock.systemUTC());

final List<PaymentTransactionsDailyFacts> list = dashboardRepository.top_daily_transactions(start_datel, end_datel);

final Collector<PaymentTransactionsDailyFacts, List<TopTerminalsDTO>, List<TopTerminalsDTO>> terminalsCollector =
Collector.of(
ArrayList::new,
(terminals, p) -> terminals.add(mapper.toTopTerminalsDTO(p)),
(accumulator, terminals) -> {
accumulator.addAll(terminals);
return accumulator;
}
);

final Map<Integer, List<TopTerminalsDTO>> final_map =
list.stream()
.filter(p -> p.getTerminal_id() != null)
.collect(Collectors.groupingBy(p -> p.getTerminal_id(), terminalsCollector));

return ResponseEntity.ok(final_map);
}

最佳答案

按照您的 JSON,testDate()应该返回 Map<String, TopTerminalsDTO>而不是 List .

Map<String, TopTerminalsDTO> result = newHashMap();

for (int i = 0; i <= 10; i++) {

TopTerminalsDTO ttDto = new TopTerminalsDTO();
ttDto.setCount(ThreadLocalRandom.current().nextInt(20, 500 + 1));

LocalDate localDate = LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

ttDto.setDate(date);
ttDto.setVolume(ThreadLocalRandom.current().nextInt(300, 5000 + 1));

result.put("terminal "+i, ttDto)
}

return result;

当然,将 rest 方法的响应类型更改为 ResponseEntity<Map<String, TopTerminalsDTO>>

关于java - 从 Rest API 返回带有值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54616738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com