I am working on consuming external API in spring boot application. I have written my JSON response that is coming from external API using RestTemplate and exchange() method of HttpEntity.
Below is the response:
String json = """
{
"links": {
"RCDSO - Production Environment Cost": {
"href": "href 1"
},
"RCDSO - Development & UAT Environment Cost": {
"href": "href 2"
},
"RCDSO - Total Cost for Prod - Compugen Managed": {
"href": "href 3"
},
"RCDSO - Virtual Machine Cost": {
"href": "href 4"
},
"RCDSO - Azure File Storage Cost": {
"href": "href 5"
},
"RCDSO - Azure Backup and Site Recovery": {
"href": "href 6"
},
"RCDSO - Azure App Services Cost": {
"href": "href 7"
}
}
}
""";
Map<String, Map<String, String>> links = JsonPath.read(json, "$.links");
links.forEach((key, value) -> {
System.out.println("k = " + key);
System.out.print("v = ");
value.forEach((key2, value2) -> {
System.out.println("key = " + key2 + " : value = " + value2);
});
});
In above code, I tried to get values from Map. Now I want to convert into my POJO class.
Below is my Pojo named OlapCustomReportResponse.java:
public class OlapCustomReportResponse {
private String name;
private String href;
}
I extracted key from outer loop and on the basis of key I extracted value from inner loop as below:
Key 1 = RCDSO - Production Environment Cost
Key 2 = href : Value 2 = some url related to key 1
Key 2 = RCDSO - Development & UAT Environment Cost
Key 2 = href : Value 2 = some url related to key 2
Key 3 = RCDSO - Total Cost for Prod - Compugen Managed
Key 2 = href : Value 2 = some url related to key 3
Key 4 = RCDSO - Virtual Machine Cost
Key 2 = href : Value 2 = some url related to key 4
.... and so on
I want my OlapCustomReportResponse.java should look something like below:
[
{
"href" : "some url of key 1",
"name" : "key 1"
},
{
"href" : "some url of key 2",
"name" : "key 2"
},
{
"href" : "some url of key 3",
"name" : "key 3"
},
{
"href" : "some url of key 4",
"name" : "key 4"
}
...... and so on...
]
My main motivation is to map or convert that result to my POJO class. How should I do or what would be the possible approach?
I am actually using com.fasterxml.jackson.databind.ObjectMapper and it is really fast, strong and a good json parser
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<HashMap<String, Map<String, String>>> typeRef = new TypeReference<HashMap<String, Map<String, String>>>() {};
Map<String, Map<String, String>> results = objectMapper.readValue(file, typeRef);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.