原因:com.fasterxml.jackson.core.JsonParseException:无法识别的令牌 'okhttp3':期待(JSON 字符串')

Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'okhttp3': was expecting (JSON String')

我正在尝试从 okhttp:

转换此响应
[
  {
    "word": "Auricomous",
    "definition": "Having golden or blond hair  ",
    "pronunciation": "Aurikomous"
  }
]

使用此代码:

        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);
        }

DTO:

public class Root{
    public String word;
    public String definition;
    public String pronunciation;
}

但我得到错误:

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]

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

response.body().toString() 上使用 response.body().string(),然后关闭 response.body().close()

.toString(): 这 returns 您的字符串格式的对象。

.string(): 这 returns 您的回复。

问题

response.body().toString()方法的调用是inherited from Objectclass和returns完整的class-name实例的十六进制hash-code:

this method returns a string equal to the value of:

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

"okhttp3.internal.http.RealResponseBody@466f95e8"。 因为这个字符串 无效 JSON,Jackson 抛出这个异常:

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'okhttp3': was expecting (JSON String

这不是您和 Jackson 的 ObjectMapper.readValue() 方法所期望的 JSON 表示。

解决方案

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

Returns the response as a string.

另请参阅: