gpt4 book ai didi

java - 以 Id 作为 Json 键的 ApiResponse 类

转载 作者:行者123 更新时间:2023-11-30 01:42:42 25 4
gpt4 key购买 nike

我正在尝试使用一些公共(public) API 中的数据,但我陷入了有关此数据设计的一些问题。我正在使用 Spring。

我正在用经典的方式来做:

private ResponseEntity<ApiResponse> getVehicules() {
final String methodUri = "/vehicules";
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

return restTemplate.exchange(apiUri + methodUri, HttpMethod.GET, entity, ApiResponse.class);
}

问题更多是关于 ApiResponse 类的设计。事实上,api 返回的 json 看起来像:

{
"status": "ok",
"meta": {
"count": 2,
"page_total": 1,
"limit": 100,
"page": null
},
"data": {
"18497": {
"id": 18497,
"name": "vehiculeName",
"nation": "vehiculeNation"
},
"52467": {
"id": 52467,
"name": "anotherVehiculeName",
"nation": "anotherVehiculeNation"
}
}
}

那么我该如何管理我的类(class)中的 id(括号前的 id - 例如 18497:{...} )?

正因为如此,我一直在尝试创建一个 Data 类,正如你可以想象的,它是一个公共(public) API,不是我的,所以我无法更改这一边的任何内容。

最佳答案

这种奇怪的 Json(在字段名称中使用动态信息)很难弄清楚如何阅读。但解决办法很简单。

您需要在 ApiResponse 类上使用 Map,例如:

class ApiResponse {

// other fields

@JsonProperty("data")
private Map<String, VehicleResponse> vehicles;

}

VehicleResponse 是一个带有 idnamenation 字段的普通类。

因此, map vehicles 将具有 key 18497 (等)和 value VehicleResponse 中有关车辆的信息(id、名称、国家)。

关于java - 以 Id 作为 Json 键的 ApiResponse 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59396356/

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