Search code examples
javajsonstringjava-15

Inserting String variable into JSON which is in a form of String


I have a JSON payload saved as a String

String jsonBody = “{\n”
            + ” \“example\“: {\n”
            + ”  \“example\“: [\n”
            + ”   {\n”
            + ”    \“example\“: 100,\n”
            + ”    \“this_is_example_json_key\“: \“this_is_example_json_value\“,\n”

I created that by copying body from i.e Postman into

String jsonBody = "here I pasted the body";

Unfortunately I cannot have everything hardcoded there, so I have to change some values to variables. The JSON in postman looks like:

"this_is_example_json_key":"x"

And so on. Let's assume that:

String x = “this_is_example_json_value“;

If I just replace it like

+ ” \“this_is_example_json_key\“: \“ + x + \“,\n”

or something like that, the value in the body will be just this_is_example_json_value, where I need "this_is_example_json_value" (the "" marks are part of the value).

So the question is, how to set up those + / " in the String, so in the end in the value of the JSON I will end up with the value inside " ".

I've tried to play with the " / + but nothing of those were working. Variable must be passed with those " " because otherwise, the API is sending back an error.


Solution

  • Since java 15, if you want only use the string, you can also do in this way:

    int this_is_example_json_value= 100;
    String json = """
    {
        "this_is_example_json_key":  %d
    }
    """.formatted(this_is_example_json_value);
    

    Here the official jep.