Making a request which returns a json response body fine in Postman, but just returns a 200 when I run my code. I'm pretty sure the classes I'm using to deserialize with Jackson are structured correctly, and the json body of the request appears to be valid. What am I missing?
Here's the class where the request is made:
import ...
@Service
public class CPService {
@Value("${cp.url}")
private String cpUrl;
@Autowired
private ObjectMapper objectMapper;
public ResponseData send(String caseId, String pId, String documentId) throws IOException {
String version = "1.0";
Request request = Request.builder()
.requestData(RequestData.builder()
.version(version)
.transactionId(caseId)
.credPublish(CredPublish.builder()
.refId(pId)
.reportDocumentId(documentId)
.build())
.build())
.build();
HttpPost httpPost = new HttpPost(cpUrl);
EntityBuilder builder = createBuilder();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setText(objectMapper.writeValueAsString(request));
httpPost.setEntity(builder.build());
try (CloseableHttpClient httpClient = createHttpClient()) {
CloseableHttpResponse response = httpClient.execute(httpPost);
ResponseData responseData = objectMapper.readValue(response.getEntity().getContent(), ResponseData.class);
return responseData;
}
}
EntityBuilder createBuilder() {
return EntityBuilder.create();
}
CloseableHttpClient createHttpClient() {
return HttpClients.createDefault();
}
}
Here are the classes used:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Data
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseData {
private Integer resultCount;
private String version;
private CredPublishResponse credPublish;
private String transactionId;
private List<ErrorMessage> errors;
}
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class CredPublishResponse {
private String responseMessage;
}
Here is an example of the response from Postman:
{
"responseData": {
"resultCount": 1,
"version": "",
"credPublish": {
"responseMessage": "success"
},
"transactionId": "CASE-1234567"
}
}
CodePudding user response:
This happens because the json response you posted is not a ResponseData
object representation but it contains a ResponseData
object representation at the "responseData" property; normally the conversion attempt would end with an error expressed with the appropriate exception but the @JsonIgnoreProperties(ignoreUnknown = true)
annotation over the class blocks the error report and then the obtained object contains just null fields.
To avoid this behaviour you can read your json at the at the "responseData" property location as a JsonNode
object and convert it to a ResponseData
object like below:
JsonNode root = mapper.readTree(response.getEntity().getContent());
ResponseData responseData = mapper.treeToValue(root.at("/responseData"), ResponseData.class);