skip to Main Content

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


  1. 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);
    

    }

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search