Issue
I receive this response:
[{"id":1,"someField":"someValue"}]
Here is my request:
private HttpRequest doRequest(String body, URI uri) {
return HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(body))
.uri(uri)
.headers(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.build();
}
and I tried to do this, but, it didn't work:
protected ClassToDecode createResponse(HttpResponse<HttpBodyCodec> response) {
return response.body().decodeAs(ClassOfResponse.class);
}
My ClassToDecode has a list of my response class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
public class ClassToDecode {
private List<ClassResponse> responses;
}
and my ClassResponse with the fields to decode:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode
public class ClassResponse {
@JsonProperty("id")
private Integer id = null;
@JsonProperty("someField")
private String someField = null;
}
Doing this way, the fields are not filled with the response. I'm not able to decode the list I receive, how should I do it?
Solution
the reason why your class ClassToDecode
doesn't work is because it's trying to find the key responses
into the the json object, something like this:
{"responses":[{"id":1,"someField":"someValue"}]}
the easiest way to do what you want is:
public class ClassToDecode extends ArrayList<ClassResponse> {
}
This should we work, and help you to decode.
regards.
Answered By - Marco
Answer Checked By - David Marino (JavaFixing Volunteer)