官术网_书友最值得收藏!

  • Spring 5.0 Projects
  • Nilang Patel
  • 186字
  • 2021-07-02 12:34:57

Designing the client for World Bank API

We need to fetch the GDP data from WorldBank API. As we discussed, it is REST end point, where we have to send few parameters and will get the response. For this, we will use RestTemplate to make REST call. The following is the definition for the com.packt.external.WorldBankApiClient class, which is used to invoke the World Bank API and process its response to return List<CountryGDP>:

@Service
public class WorldBankApiClient {

String GDP_URL = "http://api.worldbank.org/countries/%s/indicators/NY.GDP.MKTP.CD?"
+ "format=json&date=2008:2018";

public List<CountryGDP> getGDP(String countryCode) throws ParseException {
RestTemplate worldBankRestTmplt = new RestTemplate();
ResponseEntity<String> response
= worldBankRestTmplt.getForEntity(String.format(GDP_URL, countryCode), String.class);

//the second element is the actual data and its an array of object
JSONParser parser = new JSONParser();
JSONArray responseData = (JSONArray) parser.parse(response.getBody());
JSONArray countryDataArr = (JSONArray) responseData.get(1);

List<CountryGDP> data = new ArrayList<CountryGDP>();
JSONObject countryDataYearWise=null;
for (int index=0; index < countryDataArr.size(); index++) {
countryDataYearWise = (JSONObject) countryDataArr.get(index);

String valueStr = "0";
if(countryDataYearWise.get("value") !=null) {
valueStr = countryDataYearWise.get("value").toString();
}
String yearStr = countryDataYearWise.get("date").toString();
CountryGDP gdp = new CountryGDP();
gdp.setValue(valueStr != null ? Double.valueOf(valueStr) : null);
gdp.setYear(Short.valueOf(yearStr));
data.add(gdp);
}
return data;
}
}
主站蜘蛛池模板: 甘德县| 江川县| 循化| 临夏市| 天等县| 徐州市| 盐亭县| 大安市| 安平县| 南通市| 湄潭县| 普洱| 盘山县| 上饶县| 海口市| 英吉沙县| 石门县| 武山县| 玉屏| 榆林市| 阳城县| 肥东县| 巴东县| 峨眉山市| 伊宁县| 会宁县| 汉寿县| 永兴县| 明水县| 苏尼特左旗| 大安市| 鄂托克前旗| 临江市| 怀来县| 寿光市| 乌拉特前旗| 渭源县| 荆门市| 桐城市| 白水县| 霍山县|