2016-07-20 47 views
2

我給這個模型春RestTemplate獲得通用對象

public class ResponseMessage<T> { 

    private T result; 
    private ResultCode resultCode; 
    private String details; 

    public ResponseMessage(T result, ResultCode resultCode, String details) { 
     this.result = result; 
     this.resultCode = resultCode; 
     this.details = details; 
    } 
//getters and setters 

,當我從服務器獲取這個模型我conwert它

RestTemplate restTemplate = new RestTemplate(); 
     String result = restTemplate.getForObject(lkAuthListUrl, String.class); 
     Type listType = new TypeToken<ResponseMessage<LkAuth[]>>() { 
     }.getType(); 
     ResponseMessage<LkAuth[]> model = Converter.me().getModel(result, listType); 

,並在轉換器我做

public <T> T getModel(String jsonStr, Type type) { 
     T t = null; 
     try { 
      t = gson.fromJson(jsonStr, type); 
     } catch (Exception e) { 
      System.out.print(e); 
     } 
     return t; 
    } 

我可以在我的方法中避免轉換並將此職責轉移到RestTemplate

東西LILE此

ResponseMessage<LkAuth[]> model = restTemplate.getForObject(lkAuthListUrl, ResponseMessage<LkAuth[]>.class); 

回答

0

這可以通過在restTemplate對象使用exchange()方法來避免,但需要一些變化,如您的陣列與所述類型轉換爲一個List以及使ParameterizedTypeReference作爲參數(由於類型擦除而必需)。其餘部分與您所期望的類似:

ResponseEntity<List<LkAuth>> response = 
     restTemplate.exchange(lkAuthListUrl, 
        HttpMethod.GET, null, new ParameterizedTypeReference<List<LkAuth>>() {}); 
List<LkAuth> model = response.getBody();