I'm trying to convert this response from okhttp:
[
{
"word": "Auricomous",
"definition": "Having golden or blond hair ",
"pronunciation": "Aurikomous"
}
]
using this code:
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;
}
But I get error:
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]
Do you know how I can fix this issue?
CodePudding user response:
Issue
The call of response.body().toString()
method is inherited from Object
class and returns the full class-name with instance's hexadecimal hash-code:
this method returns a string equal to the value of:
getClass().getName() '@' Integer.toHexString(hashCode())
as "okhttp3.internal.http.RealResponseBody@466f95e8"
.
Because this string is no valid JSON, Jackson throws this exception:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'okhttp3': was expecting (JSON String
This is not what you and Jackson's ObjectMapper.readValue()
method expected as JSON representation.
Solution
Instead use response.body().string()
method to get the response body's textual representation as String (here JSON):
Returns the response as a string.
See also:
CodePudding user response:
Use response.body().string()
over response.body().toString()
, followed by closing the response.body().close()
.toString():
This returns your object in string format.
.string():
This returns your response.