简体   繁体   English

如何使用Jackson注释从HttpResponse反序列化JSON对象?

[英]How deserialize JSON object from HttpResponse using Jackson annotations?

I'm using the Apache http classes to call a web service that returns a JSON object in the response body. 我正在使用Apache http类来调用在响应主体中返回JSON对象的Web服务。 I have a Jackson annotated java class mapped to the JSON object. 我有一个Jackson注释的java类映射到JSON对象。 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();

You have to use the ObjectMapper : 你必须使用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) (可以重用对象映射器实例,因此不需要为每个反序列化创建新的实例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM