adam bien's blog

Java: Text Blocks + String#formatted = JSON 📎

JEP 378: Text Blocks combined with String#formatted allow inline creation of JSON objects with plain Java:


@Test
public void generateJson() {
    var message = """
        {
            "message":"%s"
        }
        """.formatted("hello,duke");
    System.out.println(message);
}

The code above prints:


{
    "message":"hello,duke"
}