javajsonstringmultilinestringjava-text-blocks

Better way to hard-code JSON data as String in Java


I need to keep JSON data in my code for unit-tests as string. For instance,

{
    "one": 1,
    "two": 2
}

I know that I can read this data from file or from property, but I need to keep them as string. Currently, I have something like this:

String s = "{\n" +
           "    \"one\": 1,\n" +
           "    \"two\": 2\n" +
           "}";

But it looks ugly and in more complex data, it is hard to read and modify it.

I may get rid of \n because they are not really needed but for pretty viewing these data later:

String s = "{" +
           "    \"one\": 1," +
           "    \"two\": 2" +
           "}";

Also, I may use a trick with quote replacement:

String s = ("{\n" +
            "    'one': 1,\n" +
            "    'two': 2\n" +
            "}").replace('\'','"');

Or combine both things at once.

Is there a better way to represent JSON data as a String in Java?

For instance, in Python, there are triple quotes:

s = """
{
    "one": 1,
    "two": 2
}
"""

Solution

  • Text Blocks - Java 15+

    If you're using Java 15 or late to represent JSON-data instead of string concatenation, which is tedious and error-prone because of the need to escape every quotation mark, you can make use of the text blocks.

    To create a text block, you need to enclose the multiline text in triple double-quote characters """.

    String myJSON = """ // no characters should appear after the opening delimiter - the text starts from the next line
    {
        "one": 1,
        "two": 2
    }""";
    

    As well as regular strings, text blocks support escape sequences, but you don't need to escape quotation marks inside a text block.

    And note that the opening delimiter """ should be immediately followed by the line termination like in the example shown above.

    Alternatives

    If your project is on a version of Java that doesn't support text blocks, but you don't want to dial with string concatenation, you can put your JSON into a text file and then read it line by line.

    With Java 11 you can read the whole file contents into a string with a single line of code by using Files.readString():

    String myJSON = Files.readString(path);