Java 13 Text Block WITHOUT newline

0 votes
723 views
asked Feb 5, 2020 by Hitesh Garg (780 points)  

In my test for a repository I have to setup an expected json which will not have any space as I have used Jackson library and the data to persist in database should not even have any space in it.
But at the same time it becomes difficult to setup the big expected json in test as it is in the same line.
Is there a way in Java 13 to skip the newline while writing the json.

Expected input

"""
{
"name":"codingeek",
"type":"blog"
}
"""

Expected output

{"name":"codingeek","type":"blog"}

1 Answer

0 votes
answered Dec 5, 2020 by Hitesh Garg (780 points)  
 
Best answer

for this, there are following possible solutions out of many available..

Use Line Terminator Escape sequence

Use '\' (backslash) at the end of each line which will escape the new line for that particular line. Details

"""
{
"name":"codingeek",\
"type":"blog"\
}
"""

Use the 'replaceAll' method on String object

Use replaceAll("\n", " ") method on the string object to replace all newline characters with the replacement of your choice.

"""
{
"name":"codingeek",
"type":"blog"
}
""".replaceAll("\n", " ");
...