导致:com.fasterxml.jackson.core.JsonParseException:无法识别的令牌“okhttp3”:正在等待(JSON字符串)

Pet*_*zov 3 java okhttp

我正在尝试从 okhttp 转换此响应:

[
  {
    "word": "Auricomous",
    "definition": "Having golden or blond hair  ",
    "pronunciation": "Aurikomous"
  }
]
Run Code Online (Sandbox Code Playgroud)

使用此代码:

        OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://random-words-api.vercel.app/word")
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response body

            ObjectMapper objectMapper = new ObjectMapper();
            String responseBody = response.body().toString();
            Root[] root = objectMapper.readValue(responseBody, Root[].class);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
Run Code Online (Sandbox Code Playgroud)

数据传输对象:

public class Root{
    public String word;
    public String definition;
    public String pronunciation;
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

Caused by: java.lang.RuntimeException: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'okhttp3': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (String)"okhttp3.internal.http.RealResponseBody@466f95e8"; line: 1, column: 8]
    at com.wordscore.engine.service.generator.WordsGeneratorImpl.generateRandomKeyword(WordsGeneratorImpl.java:47)
    at com.wordscore.engine.processor.KeywordPostJob.execute(KeywordPostJob.java:21)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
    ... 1 common frames omitted
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'okhttp3': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (String)"okhttp3.internal.http.RealResponseBody@466f95e8"; line: 1, column: 8]
Run Code Online (Sandbox Code Playgroud)

你知道我该如何解决这个问题吗?

hc_*_*dev 5

问题

方法的调用response.body().toString()Object类继承的,并返回带有实例的十六进制哈希码的完整类名:

此方法返回一个等于以下值的字符串:

getClass().getName() + '@' + Integer.toHexString(hashCode())

作为"okhttp3.internal.http.RealResponseBody@466f95e8"。因为该字符串不是有效的 JSON,所以 Jackson 抛出此异常:

com.fasterxml.jackson.core.JsonParseException:无法识别的令牌“okhttp3”:正在等待(JSON字符串

这不是你和杰克逊的ObjectMapper.readValue()方法所期望的 JSON 表示形式。

解决方案

而是使用response.body().string()方法来获取响应正文的文本表示形式为字符串(此处为 JSON):

以字符串形式返回响应。

也可以看看: