为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 453 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号