httpclient请求方式下的泛型json转换问题

我们在采用httpclient方式进行服务调用时,如果服务方以对象的方式封装入参和出参,我们就经常需要将我们的请求对象先转换成 json 格式,通过输入输出流的方式传输数据,返回的参数再从 json 格式转换为特定对象,如下:

Producer producer = new Producer();
...构造参数...
String jsonData = GsonUtils.toJson(producer);
...httpclient请求...
Consumer consumer = GsonUtils.fromJson(jsonResult, Consumer.class);


采用这种方式,可以很容易得到想要的结果,但如果服务方返回的是泛型对象就麻烦了,如下:

GenericResult<Consumer> result = GsonUtils.fromJson(jsonResult,GenericResult.class);


这样是可以得到返回的内容,甚至还能在前端取到 result 对象中的基本类型数据,但自定义对象数据就无法取到了。如果使用 Consumer consumer = result.getConsumer(); 就会报错,如下"java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Consumer"之类的类型转换错误,因为泛型转换过程中如果直接使用父类类型从 json 格式转换过来,他是没办法再转换成相应的子类的。更具体的原因是由于Java泛型的实现机制,使用了泛型的代码在运行期间相关的泛型参数的类型会被擦除,我们无法在运行期间获知泛型参数的具体类型(所有的泛型类型在运行时都是Object类型)。

解决方法有两种,一种是直接使用resteasy的调用方式,那么根本就不存在这种问题;另一个就是借助 typeToken,只要将需要获取类型的泛型类作为TypeToken的泛型参数构造一个匿名的子类,就可以通过getType()方法获取到我们使用的泛型类的泛型参数类型。代码如下:

Producer producer = new Producer();
...构造参数...
String jsonData = GsonUtils.toJson(producer);
...httpclient请求...
Type type = new TypeToken<GenericResult<Consumer>>(){}.getType();
GenericResult<Consumer> result = (GenericResult<Consumer>)GsonUtils.fromJson(jsonResult, type);
Consumer consumer = result.getConsumer();


这时 consumer 对象就能够正确识别了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用HttpClient发送GET请求获取JSON数据,并将其输出到控制台。以下是一个示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONObject; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(); request.setURI(new URI("https://jsonplaceholder.typicode.com/todos/1")); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = in.readLine()) != null) { result.append(line); } JSONObject jsonObject = new JSONObject(result.toString()); System.out.println(jsonObject.toString()); EntityUtils.consume(response.getEntity()); } } ``` 此代码将向`https://jsonplaceholder.typicode.com/todos/1`发送GET请求,并将返回的JSON数据输出到控制台。请注意,我们创建了一个`HttpClient`实例并使用它来执行请求。在响应中,我们读取实体内容并将其转换为字符串。然后,我们将字符串转换为`JSONObject`并将其输出到控制台。最后,我们将实体内容消耗掉,以便可以重复使用连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值