亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 7:將 GET 響應轉換為通用對象的通用方法

Java 7:將 GET 響應轉換為通用對象的通用方法

慕妹3146593 2022-06-08 17:32:14
我有一個自定義通用方法,它GET向 URL 發出請求并將 JSON 響應轉換為responseType對象:public static <T> Object getForEntity(String url, Class<T> responseType) throws InterruptedException, ExecutionException, IOException{        Response getResponse = callWithHttpGet(url);        String getResponseJson = getResponse.getBody();        ObjectMapper getResponseJsonMapper = new ObjectMapper();        Object obj = getResponseJsonMapper.readValue(getResponseJson, responseType);                return obj;    }如果我將其稱為如下代碼,則上面的代碼可以正常工作:Object person = getForEntity(PERSON_REST_URL,Person.class);如何使其如下工作而不是返回對象?Person person = getForEntity(PERSON_REST_URL, Person.class);
查看完整描述

3 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

首先,讓方法返回T而不是Object:


public static <T> T getForEntity(...)

然后,實現它以返回一個 T。readValue返回正確的類,因為您傳入了Class<T>并且它的簽名也等同于public <T> T readValue(..., Class<T> clazz),所以您可以這樣做:


T obj = getResponseJsonMapper.readValue(getResponseJson, responseType);        

return obj;


查看完整回答
反對 回復 2022-06-08
?
慕后森

TA貢獻1802條經驗 獲得超5個贊

您只需要傳遞一個Class<T>參數。


請注意,您不需要對readValue方法響應進行強制轉換,因為您已經clazz作為參數傳遞,因此它返回一個clazz元素。


您的錯誤只是您將結果分配給了 Object 類型的對象。比退貨了。刪除不必要的賦值并直接從對 的調用結果中返回readValue。


public static <T> T getForEntity(String url, Class<T> clazz)  throws InterruptedException, 

                                                  ExecutionException, IOException {

    Response getResponse = callWithHttpGet(url);

    String getResponseJson = getResponse.getBody();

    ObjectMapper getResponseJsonMapper = new ObjectMapper();

    return getResponseJsonMapper.readValue(getResponseJson, clazz);        

}


查看完整回答
反對 回復 2022-06-08
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

使用 T 作為返回參數并進行強制轉換(假設可以進行強制轉換 - 否則會出現運行時異常)。


public static <T> T getForEntity(String url, Class<T> responseType) throws InterruptedException, ExecutionException, IOException{

    Response getResponse = callWithHttpGet(url);

    String getResponseJson = getResponse.getBody();

    ObjectMapper getResponseJsonMapper = new ObjectMapper();

    T obj = (T)getResponseJsonMapper.readValue(getResponseJson, responseType);        

    return obj;

}

而且在特定情況下,您甚至可以跳過演員表(如果 ObjectMapper 已經返回正確的類型 - 例如杰克遜)。


查看完整回答
反對 回復 2022-06-08
  • 3 回答
  • 0 關注
  • 440 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號