我有这样的回应
{
"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"
}
}
我想把上述JSONMap到ReportResponse.java POJO类中。
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对象,然后尝试将其转换为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类。
1条答案
按热度按时间92dk7w1h1#
您可以通过以下方式进行检查:https://json2csharp.com/code-converters/json-to-pojo以使用对象Map器进行Map
如果您的7行将始终相同,或者只是使用单个条目列表(pojo)创建ReportResponse并Map到obj,例如ReportEntry(name,href),则只需将此列表作为响应返回