簡體   English   中英

如何在spring boot中從Json響應中獲取隨機數據?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM