[英]How to convert JSON Object to JSON Array and map it to custom POJO?
我有這樣的回應
{
"RCDSO - Production Environment Cost": {
"href": "href1"
},
"RCDSO - Development & UAT Environment Cost": {
"href": "href2"
},
"RCDSO - Total Cost for Prod - Compugen Managed": {
"href": "href3"
},
"RCDSO - Virtual Machine Cost": {
"href": "href4"
},
"RCDSO - Azure File Storage Cost": {
"href": "href5"
},
"RCDSO - Azure Backup and Site Recovery": {
"href": "href6"
},
"RCDSO - Azure App Services Cost": {
"href": "href7"
}
}
我想把JSON上面的map改成ReportResponse.java POJO class。
public class ReportResponse {
private String name;
private String href;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
這樣當我通過我的 Rest API 返回 JSON 時,響應應該如下所示:
{
"response":[
{
"name" : "RCDSO - Production Environment Cost",
"href" : "href1"
},
{
"name" : "RCDSO - Development & UAT Environment Cost",
"href" : "href2"
},
{
"name" : "RCDSO - Total Cost for Prod - Compugen Managed",
"href" : "href3"
}
..... so on....
]
}
我試圖從外部 API 獲得響應並從中提取 json object 然后嘗試將其轉換為 json 數組。
public String getReportList(String clientApiId) {
String response = null;
ResponseEntity<String> responseEntity = null;
try {
final String url = "https://chapi.cloudhealthtech.com/olap_reports/custom?client_api_id="+clientApiId;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
header.add(HttpHeaders.ACCEPT, "application/json");
HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
response = responseEntity.getBody();
JSONObject obj = new JSONObject(response);
JSONObject linkJsonObj = obj.getJSONObject("links");
Iterator itr = linkJsonObj.keys();
JSONArray array = new JSONArray();
while(itr.hasNext()) {
String key = (String)itr.next();
array.put(linkJsonObj.get(key));
}
System.out.println("Json Array : "+array);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return response;
}
請幫助我實現預期的 JSON 和 map 到 ReportResponse.java POJO class。
您可以使用 ObjectMapper 檢查: https://json2csharp.com/code-converters/json-to-pojo到 map
如果您的 7 行將始終相同或只是創建 ReportResponse 與單條目列表 (pojo) 和 map 到 obj eg ReportEntry (name, href) 然后只返回此列表作為響應
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.