猿问

Java 7:将 GET 响应转换为通用对象的通用方法


我有一个自定义通用方法,它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);


慕妹3146593
浏览 454回答 3
3回答

慕工程0101907

首先,让方法返回T而不是Object:public static <T> T getForEntity(...)然后,实现它以返回一个 T。readValue返回正确的类,因为您传入了Class<T>并且它的签名也等同于public <T> T readValue(..., Class<T> clazz),所以您可以这样做:T obj = getResponseJsonMapper.readValue(getResponseJson, responseType);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;return obj;

慕后森

您只需要传递一个Class<T>参数。请注意,您不需要对readValue方法响应进行强制转换,因为您已经clazz作为参数传递,因此它返回一个clazz元素。您的错误只是您将结果分配给了 Object 类型的对象。比退货了。删除不必要的赋值并直接从对 的调用结果中返回readValue。public static <T> T getForEntity(String url, Class<T> clazz)&nbsp; throws InterruptedException,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ExecutionException, IOException {&nbsp; &nbsp; Response getResponse = callWithHttpGet(url);&nbsp; &nbsp; String getResponseJson = getResponse.getBody();&nbsp; &nbsp; ObjectMapper getResponseJsonMapper = new ObjectMapper();&nbsp; &nbsp; return getResponseJsonMapper.readValue(getResponseJson, clazz);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}

白板的微信

使用 T 作为返回参数并进行强制转换(假设可以进行强制转换 - 否则会出现运行时异常)。public static <T> T getForEntity(String url, Class<T> responseType) throws InterruptedException, ExecutionException, IOException{&nbsp; &nbsp; Response getResponse = callWithHttpGet(url);&nbsp; &nbsp; String getResponseJson = getResponse.getBody();&nbsp; &nbsp; ObjectMapper getResponseJsonMapper = new ObjectMapper();&nbsp; &nbsp; T obj = (T)getResponseJsonMapper.readValue(getResponseJson, responseType);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return obj;}而且在特定情况下,您甚至可以跳过演员表(如果 ObjectMapper 已经返回正确的类型 - 例如杰克逊)。
随时随地看视频慕课网APP

相关分类

Java
我要回答