我正在尝试使用一些公共(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
是一个带有 id
、name
、nation
字段的普通类。
因此, map vehicles
将具有 key
18497
(等)和 value
VehicleResponse
中有关车辆的信息(id、名称、国家)。
关于java - 以 Id 作为 Json 键的 ApiResponse 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59396356/