-1

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\": true\n" +
        "    }\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?

wheelerlc64
  • 435
  • 2
  • 5
  • 17
  • Does this answer your question? [How to including variables within strings?](https://stackoverflow.com/questions/9643610/how-to-including-variables-within-strings) – Chaosfire Jul 05 '23 at 19:43

2 Answers2

0

One approach is to concatenate in the json like this.

public ResponseEntity test()  {
    String doubleAsInput = String.valueOf(2.0);
    String intAsInput = String.valueOf(3);
    String stringWithSlash = "\failed";
    String valueWithComma = "comma,";
String messageValue = "Weekend UI Validation email will be shared shortly";
String statusValue = "Success";


ObjectMapper objectMapper = new ObjectMapper();
ObjectNode bodyNode = objectMapper.createObjectNode();

ObjectNode contextNode = bodyNode.putObject("@context");
contextNode.put("@type", "MessageCard");

bodyNode.put("@type", "MessageCard");
bodyNode.put("themeColor", "#00FF00");
bodyNode.put("summary", "Weekend UI Validation Success");

ArrayNode sectionsArrayNode = bodyNode.putArray("sections");
ObjectNode sectionNode = sectionsArrayNode.addObject();
sectionNode.put("activityTitle", "Weekend UI Validation Succesful!!");
sectionNode.put("activitySubtitle", "Build Results");
sectionNode.put("activityImage", "https://ac-buckets-dev-acpublicmedia-2cxkd4j0deg1.s3.amazonaws.com/icons/GreenThumbUP.png");
sectionNode.put("markdown", true);

ArrayNode factsArrayNode = sectionNode.putArray("facts");
factsArrayNode.add(createFactNode("Message", messageValue, objectMapper));
factsArrayNode.add(createFactNode("Status", statusValue, objectMapper));
factsArrayNode.add(createFactNode("Total Tests:", doubleAsInput, objectMapper));
factsArrayNode.add(createFactNode("Passed:", intAsInput, objectMapper));
factsArrayNode.add(createFactNode("Failed:", stringWithSlash, objectMapper));
factsArrayNode.add(createFactNode("Skipped", valueWithComma, objectMapper));


String requestBody = null;
try {
    requestBody = objectMapper.writeValueAsString(bodyNode);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

return ResponseEntity.ok(requestBody);

}

  • @Chiamka Etchie thanks for the suggestion. In this case it is a simple int represented in String value, but I can see what you mean if it becomes a little more complex when converting your data types to Strings required escape for certain characters. What would be the better approach for a more future proof way of preventing that? – wheelerlc64 Jul 05 '23 at 19:54
  • I have edited with a better approach to solving it, Its very modularized this way, easier to test and is future proof. – Chiamaka Etchie Jul 05 '23 at 20:12
0

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.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 08 '23 at 17:56