-1

I get this String from my database:

Test Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item ZusammenführenTest Action Item Zusammenführen
fsd
fsa
df
asdf
as
dfs
fd
sad
f
sadf
sad

Now I need to encode all LineBreaks to \n so I can produce proper JSON objects out of the String because JSON doesn't support linebreaks. How can I detect and replace all LineBreaks in the existing String with \n?

I already tried .replace() and replaceAll(). But I need a way to detect the linebreaks First so I can replace them.

Some additional informations:

After trying out several replace-functions mentioned here the JSON still looks like this:

   { "id": 182, 
     "status": "eing", 
     "text": "KORE_AI_6", 
     "beschreibung": "Eins
Zwei
Drei",
         "tags": "KORE" 
       }, 

And it should look like

   { "id": 182, 
     "status": "eing", 
     "text": "KORE_AI_6", 
     "beschreibung": "Eins\nZwei\nDrei",
     "tags": "KORE" 
   },
Tobias Kuess
  • 739
  • 2
  • 14
  • 33
  • 1
    If the line breaks you have are not `\n`, what are they? – khelwood Nov 05 '15 at 16:30
  • Unfortunately a search for \n dies Not get Any results. I Dont know, this is why i am asking. – Tobias Kuess Nov 05 '15 at 16:40
  • can you also post the code that searches for `\n` ? Is the string in your question the actual string you get from the db or something you see with a viewer ? – Manos Nikolaidis Nov 05 '15 at 16:43
  • 1
    If the lines aren't separated by `\n`, perhaps they are separated by Unicode line separators or paragraph separators. Try `s.replaceAll("[\\p{Zl}\\p{Zp}]|\\r?\\n", "\n")`. – VGR Nov 05 '15 at 17:16
  • I know tried your solution VGR, but sadly the JSON object still hast its linebreaks and not /n. – Tobias Kuess Nov 06 '15 at 08:17

2 Answers2

0

If the String you get from the database is called jsonString you can use this regex :

String result = jsonString.replaceAll("[\r\n]+", "\n");

This will match the most common line breaks \r\n \n \r. Mind you, this will also replace multiple empty lines with one empty line.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • I tried your solution, but the JSON string still has linebreaks which cause errors in the JSON parser of the client. – Tobias Kuess Nov 06 '15 at 08:18
0

I solved this problem for me. Unfortunately it seems like that .replace() like stated above in other comments and answers did the job, but the map.put() operations after reverted the changes again.

To solve it I used the StringEscapeUtils from org.apache.commons.lang3.StringEscapeUtils and used the escapeJson() method like this:

escapeUtils.escapeJson(map.get("BESCHREIBUNG").toString())
Tobias Kuess
  • 739
  • 2
  • 14
  • 33