美文网首页SpringSpring 源码大数据
如何将从http接口中获取的JSON数据转换为指定对象

如何将从http接口中获取的JSON数据转换为指定对象

作者: 勿念及时雨 | 来源:发表于2019-07-26 00:29 被阅读78次

    在实际应用开发中,我们可能经常会在调用某个接口时得到一串JSON字符串,这时我们需要把JSON字符串转换成对应的Bean对象。在SpringBoot中,我们又该如何来进行JSON字符串和Bean的转换呢?我们以调用天气接口返回JSON数据为例来进行说明。
    1.首先使用RestTemplate对象调用http请求,获得返回对象。

    ResponseEntity<String> respString=restTemplate.getForEntity(uri,String.class);
    

    2.判断返回对象的状态码,如果这个状态码是200则说明响应成功,这时再获取返回对象的内容,这里的内容是JSON格式的字符串。

    if(respString.getStatusCodeValue()==200) {
      String strBody=respString.getBody();
    }
    

    3.创建ObjectMapper对象。

    ObjectMapper mapper=new ObjectMapper();
    

    4.调用ObjectMapper的readValue()方法,传入内容和目标对象,这样就可以将内容转换成目标对象了,需要注意的是这里需要捕获或者抛出异常。

    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访问对象
    
        /**
         * 获取天气数据(先查redis再访问天气服务接口)
         * @param uri
         * @return
         */
        private WeatherResponse doGetWeather(String uri){
            String strBody=null;
            WeatherResponse resp=null;
            //访问天气接口,获得数据
            ResponseEntity<String> respString=restTemplate.getForEntity(uri,String.class);
            //解析JSON字符串数据
            if(respString.getStatusCodeValue()==200) {//判断响应对象的状态码,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;
        }
    

    相关文章

      网友评论

        本文标题:如何将从http接口中获取的JSON数据转换为指定对象

        本文链接:https://www.haomeiwen.com/subject/qljlrctx.html