如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象? [英] How deserialize JSON object from HttpResponse using Jackson annotations?
本文介绍了如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Apache http 类调用在响应正文中返回 JSON 对象的 Web 服务.我有一个映射到 JSON 对象的 Jackson 注释的 java 类.我想做这件事,但谷歌没有找到正确的样板.
I'm using the Apache http classes to call a web service that returns a JSON object in the response body. I have a Jackson annotated java class mapped to the JSON object. I want to do something this, but google hasn't turned up the correct boilerplate.
String url = hostName + uri;
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpclient.execute(httpGet);
MyObject myObject = (MyObject)response.getEntity().getContent();
推荐答案
你必须使用 ObjectMapper
:
You have to use the ObjectMapper
:
MyObject myObject = objectMapper.readValue(response.getEntity().getContent(), MyObject.class);
(一个对象映射器实例可以重复使用,所以不需要为每个反序列化创建一个新的)
(An object mapper instance can be reused, so no need to create a new one for each deserialization)
这篇关于如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文