Wednesday, 15 May 2013

Rest Template WebService Call & Map Json Response In To Java Entity

Step 1. Make a RestTemplate instance
private RestTemplate restTemplate = new RestTemplate();

Step 2. Call Post method of RestTemplate to hit the service

String jsonString = "{"
      + "\"dataBeginIndex\":\"1\"" + ","
         + "\"userId\":\"jFB425S0Rv0=\"" + ","
         + "\"countryId\":\"96\"" +","
         + "\"dataEndIndex\":\"2\""
         + "}";
      
     
  HttpHeaders headers = new HttpHeaders();
         headers.setContentType( MediaType.APPLICATION_JSON );
         
         HttpEntity customReq = new HttpEntity( jsonString, headers );
         String returnedString = restTemplate.postForObject( "http://URL", customReq, String.class );
         log.info("Response Json: "+returnedString);
         
         CustomUtil obj = new CustomUtil();
         CustomBean customBean = obj.jsonConvertor(returnedString);
Step 3. jsonConvertor(String json)
public CustomBean jsonConvertor(String jsonString)
 {
  JsonFactory factory = new JsonFactory();
  ObjectMapper mapper = new ObjectMapper(factory);
  try 
  {
   CustomBean customBean = mapper.readValue(jsonString, CustomBean.class);
   
   return customBean;
  } catch (JsonParseException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
   return new CustomBean();
 }
Step 4. Add this bean in applicationcontext

  
      
       
           
            
           
       
      
    

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...