7

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
}
"""
2
  • 2
    I believe current versions of Java support multiline strings via text blocks via an identical three-quote syntax to that you have presented. Commented Jun 18, 2022 at 5:46
  • You could also consider writing your tests in Kotlin, as multi-line strings are available there (kotlinlang.org/docs/basic-types.html#string-literals) and you could benefit from other Kotlin features (I find backticks to allow function names to have spaces are nice for tests). Commented Jun 18, 2022 at 5:50

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.