[英]How to get random data from Json response in spring boot?
我有一個來自 API 的項目列表。 我只想將一個元素作為 JSON 響應返回,它可以是隨機元素或第一個元素。
public Result makeGETApiRequest() {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.add("Authorization", "Bearer " + apiKey);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Result> response = restTemplate.exchange(url, HttpMethod.GET, entity, Result.class);
return response.getBody();
}
結果.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Result implements Serializable {
List<Records> records;
//getter and setter
}
class Records {
Fields fields;
//getter and setter
}
class Fields {
@JsonProperty("Bank")
String bank;
@JsonProperty("Credit Card Count")
int creditCardCount;
@JsonProperty("Debit Card Count")
int debitCardCount;
}
使函數makeGETApiRequest
返回Records
並在api
主體句柄中獲得一個隨機元素
像這樣:
public Result makeGETApiRequest() {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
headers.add("Authorization", "Bearer " + apiKey);
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<Result> response = restTemplate.exchange(url, HttpMethod.GET, entity, Result.class);
Random rand = new Random();
return response.getBody().getRecords.get(rand.nextInt(response.getBody().getRecords().size() - 1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.