I currently have a JSON request body as a string that I am also passing as a string in the BodyPublishers.ofString() method when using the java httpclient to send a POST request. I also want to be able to include the variables below in my values under facts as seen below:
String totalString = String.valueOf(total);
String successString = String.valueOf(success);
String failedString = String.valueOf(failed);
String skippedString = String.valueOf(skipped);
String body = "{n" +
" "@type": "MessageCard",n" +
" "@context": "http://schema.org/extensions",n" +
" "themeColor": "#00FF00",n" +
" "summary": "Weekend UI Validation Success",n" +
" "sections": [n" +
" {n" +
" "activityTitle": "Weekend UI Validation Succesful!!",n" +
" "activitySubtitle": "Build Results",n" +
" "activityImage": "https://ac-buckets-dev-acpublicmedia-2cxkd4j0deg1.s3.amazonaws.com/icons/GreenThumbUP.png",n" +
" "facts": [n" +
" {n" +
" "name": "Message",n" +
" "value": " Weekend UI Validation email will be shared shortly"n" +
" },n" +
" {n" +
" "name": "Status",n" +
" "value": "Success"n" +
" },n" +
" {n" +
" "name": "Total Tests: ",n" +
" "value": "Needs to be totalString"n" +
" },n" +
" {n" +
" "name": "Passed: ",n" +
" "value": "Needs to be totalString"n" +
" },n" +
" {n" +
" "name": "Failed: ",n" +
" "value": "Needs to be failedString"n" +
" },n" +
" {n" +
" "name": "Skipped",n" +
" "value": "Needs to be skippedString"n" +
" }n" +
" ],n" +
" "markdown": truen" +
" }n" +
" ]n" +
"}";
Using the java net http client, I have the below method, where the request body is passed as String in the POST method which accepts the request body string:
public HttpResponse sendTeamsPostSummary(String url, String reqBody) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(BodyPublishers.ofString(reqBody))
.setHeader("Content-Type", "application/json")
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response);
return response;
}
How can I do this in such a way where the value of value within the facts json object can be passed with the variable instead of a hardcoded string?
2
Answers
One approach is to concatenate in the json like this.
}
I highly recommend taking a look at a JSON serialization library, such as Jackson Databind. Based on your comment to Chiamaka Etchie’s answer, it seems like you are trying to convert your data types to strings, which is MUCH easier when you use an existing serialization library.