[英]How to get random data from Json response in spring boot?
I have a list of items from an API.我有一个来自 API 的项目列表。 I want only one element to be returned as JSON response which can be the random or first element.
我只想将一个元素作为 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();
}
Result.java结果.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;
}
Make the function makeGETApiRequest
return Records
and in the api
body handle that you get a random element使函数
makeGETApiRequest
返回Records
并在api
主体句柄中获得一个随机元素
like this:像这样:
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.