1. Introduction
1.绪论
In this tutorial, we’ll explore several techniques for decoding a JSON response while using OkHttp.
在本教程中,我们将探讨在使用OkHttp时对JSON响应进行解码的几种技术。
2. OkHttp Response
2.OkHttp Response
OkHttp is an HTTP client for Java and Android with features like transparent handling of GZIP, response caching, and recovery from network problems.
OkHttp是一个适用于Java和Android的HTTP客户端,具有透明处理GZIP、响应缓存和从网络问题中恢复等功能。
In spite of these great features, OkHttp doesn’t have a built-in encoder/decoder for JSON, XML, and other content types. However, we can implement these with the help of XML/JSON binding libraries, or we can use high-level libraries like Feign or Retrofit.
尽管有这些伟大的功能,OkHttp并没有一个内置的JSON、XML和其他内容类型的编码器/解码器。然而,我们可以在XML/JSON绑定库的帮助下实现这些,或者我们可以使用像Feign或Retrofit的高级库。
To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object. The ResponseBody class has several options for extracting this data:
为了实现我们的JSON解码器,我们需要从服务调用的结果中提取JSON。为此,我们可以通过Response对象的body()方法访问主体。ResponseBody类有几个选项用于提取这些数据。
- byteStream(): exposes the raw bytes of the body as an InputStream; we can use this for all formats, but usually it is used for binaries and files
- charStream(): when we have a text response, charStream() wraps its InputStream in a Reader and handles encoding according to the response’s content type or “UTF-8” if charset isn’t set in the response header; however, when using charStream(), we can’t change the Reader‘s encoding
- string(): returns the whole response body as a String; manages the encoding the same as charStream(), but if we need a different encoding, we can use source().readString(charset) instead
In this article, we’re going to use string() since our response is small and we don’t have memory or performance concerns. The byteStream() and charStream() methods are better choices in production systems when performance and memory matter.
在本文中,我们将使用string(),因为我们的响应很小,而且我们没有内存或性能的问题。byteStream()和charStream()方法是生产系统中性能和内存重要时的更好选择。
To start, let’ s add okhttp to our pom.xml file:
首先,让我们把okhttp添加到我们的 pom.xml 文件中。
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
</dependency>
And then, we model the SimpleEntity to test our decoders:
然后,我们为SimpleEntity建模,以测试我们的解码器。
public class SimpleEntity {
protected String name;
public SimpleEntity(String name) {
this.name = name;
}
// no-arg constructor, getters, and setters
}
Now, we’re going to initiate our test:
现在,我们要启动我们的测试。
SimpleEntity sampleResponse = new SimpleEntity("Baeldung");
OkHttpClient client = // build an instance;
MockWebServer server = // build an instance;
Request request = new Request.Builder().url(server.url("...")).build();
3. Decode the ResponseBody with Jackson
3.用Jackson解码ResponseBody
Jackson is one of the most popular libraries for JSON-Object binding.
Jackson是用于JSON-Object绑定的最流行的库之一。
Let’s add jackson-databind to our pom.xml:
让我们把jackson-databind加入我们的pom.xml中。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
Jackson’s ObjectMapper lets us convert JSON to an object. Thus, we can decode the response using ObjectMapper.readValue():
Jackson的ObjectMapper让我们将JSON转换为一个对象。因此,我们可以使用ObjectMapper.readValue()对响应进行解码。
ObjectMapper objectMapper = new ObjectMapper();
ResponseBody responseBody = client.newCall(request).execute().body();
SimpleEntity entity = objectMapper.readValue(responseBody.string(), SimpleEntity.class);
Assert.assertNotNull(entity);
Assert.assertEquals(sampleResponse.getName(), entity.getName());
4. Decode the ResponseBody with Gson
4.用Gson解码ResponseBody
Gson is another useful library for mapping JSON to Objects and vice versa.
Gson是另一个有用的库,用于将JSON映射到对象,反之亦然。
Let’s add gson to our pom.xml file:
让我们把gson添加到我们的pom.xml文件。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Let’s see how we can use Gson.fromJson() to decode the response body:
让我们看看如何使用Gson.fromJson() 来解码响应体。
Gson gson = new Gson();
ResponseBody responseBody = client.newCall(request).execute().body();
SimpleEntity entity = gson.fromJson(responseBody.string(), SimpleEntity.class);
Assert.assertNotNull(entity);
Assert.assertEquals(sampleResponse.getName(), entity.getName());
5. Conclusion
5.总结
In this article, we’ve explored several ways to decode the JSON response of OkHttp with Jackson and Gson.
在这篇文章中,我们已经探讨了用Jackson和Gson解码OkHttp的JSON响应的几种方法。
The complete sample is available on over on GitHub.
完整的样本可在GitHub上找到。