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

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;
}
}
主站蜘蛛池模板: 海盐县| 东兰县| 曲松县| 长寿区| 股票| 铜鼓县| 闻喜县| 来宾市| 合山市| 桑植县| 宁乡县| 永济市| 鄂托克前旗| 马龙县| 兴仁县| 通许县| 余姚市| 梧州市| 子长县| 柘城县| 开江县| 黄山市| 香格里拉县| 株洲市| 东乡族自治县| 南江县| 陆河县| 宕昌县| 陈巴尔虎旗| 康保县| 萝北县| 葫芦岛市| 西宁市| 萍乡市| 清苑县| 仁布县| 吐鲁番市| 仪陇县| 石首市| 平湖市| 昆山市|