在實(shí)際應(yīng)用開發(fā)中背亥,我們可能經(jīng)常會在調(diào)用某個(gè)接口時(shí)得到一串JSON字符串,這時(shí)我們需要把JSON字符串轉(zhuǎn)換成對應(yīng)的Bean對象盔粹。在SpringBoot中隘梨,我們又該如何來進(jìn)行JSON字符串和Bean的轉(zhuǎn)換呢?我們以調(diào)用天氣接口返回JSON數(shù)據(jù)為例來進(jìn)行說明舷嗡。
1.首先使用RestTemplate對象調(diào)用http請求轴猎,獲得返回對象。
ResponseEntity<String> respString=restTemplate.getForEntity(uri,String.class);
2.判斷返回對象的狀態(tài)碼进萄,如果這個(gè)狀態(tài)碼是200則說明響應(yīng)成功捻脖,這時(shí)再獲取返回對象的內(nèi)容锐峭,這里的內(nèi)容是JSON格式的字符串。
if(respString.getStatusCodeValue()==200) {
String strBody=respString.getBody();
}
3.創(chuàng)建ObjectMapper對象可婶。
ObjectMapper mapper=new ObjectMapper();
4.調(diào)用ObjectMapper的readValue()方法沿癞,傳入內(nèi)容和目標(biāo)對象,這樣就可以將內(nèi)容轉(zhuǎn)換成目標(biāo)對象了矛渴,需要注意的是這里需要捕獲或者拋出異常椎扬。
try {
WeatherResponse resp=mapper.readValue(strBody,WeatherResponse.class);
}catch(IOException e){
e.printStackTrace();
}
最后貼出完整的代碼:
private Logger logger=LoggerFactory.getLogger(WeatherDataServiceImpl.class);
@Autowired
private RestTemplate restTemplate;//http訪問對象
/**
* 獲取天氣數(shù)據(jù)(先查redis再訪問天氣服務(wù)接口)
* @param uri
* @return
*/
private WeatherResponse doGetWeather(String uri){
String strBody=null;
WeatherResponse resp=null;
//訪問天氣接口,獲得數(shù)據(jù)
ResponseEntity<String> respString=restTemplate.getForEntity(uri,String.class);
//解析JSON字符串?dāng)?shù)據(jù)
if(respString.getStatusCodeValue()==200) {//判斷響應(yīng)對象的狀態(tài)碼具温,200表示成功
strBody=respString.getBody();
}
ObjectMapper mapper=new ObjectMapper();
try {
resp=mapper.readValue(strBody,WeatherResponse.class);
}catch(IOException e){
//e.printStackTrace();
logger.error("errorInfo{}",e.getMessage());
}
return resp;
}