-2

Hello I need help replacing "\" character with "/" character in Java. This is my code:

        json = "{\"fields\": {" +
                "                    \"project\":" +
                "                            {" +
                "                                    \"key\": \"key\"" +
                "                            }," +
                "                    \"summary\": \"" + paramMap.get("summary")[0] + "\"," +
                "                    \"description\": \"" + paramMap.get("description")[0].replaceAll("[\r]{1}", "").replaceAll("\n","\\\\n").replace('\\', '/')+ "\"," +
                "                   \"reporter\": {" +
                "                           \"name\": \"" + reporter.getName() + "\"" +
                "        },"+
                "                    \"issuetype\": {" +
                "                            \"id\": \"000000\"" +
                "                    }," +
                something.toString() +
                somethingelse.toString() +
        "   }" +
                "}";

This is a mess and I need this JSON not to have backslashes in my text (description). so I added replace('\\', '/') there

Unfortunately this turns all new line symbols ("\n") into "/n". I need to avoid this and also keep the original code Is there a better way to replace "" in Java OR to exclude "\n" from replacement? Thanks

Example stirng:

Lorem ip\sum dolor sit amet ,

consectetur adipiscing elit. Proin et metus eget massa facilisis ultricies sit amet sit amet mi. Donec in hendrerit justo. Ut ut

enim vehicu la metus ullamcorper lacinia sit amet fe ugiat sem. Vivamus t empor eros consequat felis tempus tincidunt. Nullam h endrerit orci dictum dolor volutpat, in maximus lorem imperdiet. Aliquam

tristique nunc nec tellus pretium luctus. Nulla suscipit non magna ac bibendum.

Desired output:

Lorem ip/sum dolor sit amet ,

consectetur adipiscing elit. Proin et metus eget massa facilisis ultricies sit amet sit amet mi. Donec in hendrerit justo. Ut ut

enim vehicu la metus ullamcorper lacinia sit amet fe ugiat sem. Vivamus t empor eros consequat felis tempus tincidunt. Nullam h endrerit orci dictum dolor volutpat, in maximus lorem imperdiet. Aliquam

tristique nunc nec tellus pretium luctus. Nulla suscipit non magna ac bibendum.

Actual output:

Lorem ip/sum dolor sit amet , /nconsectetur adipiscing elit. Proin et metus eget massa facilisis ultricies sit amet sit amet mi. Donec in hendrerit justo. Ut ut /nenim vehicu la metus ullamcorper lacinia sit amet fe ugiat sem. Vivamus t empor eros consequat felis tempus tincidunt. Nullam h endrerit orci dictum dolor volutpat, in maximus lorem imperdiet. Aliquam /ntristique nunc nec tellus pretium luctus. Nulla suscipit non magna ac bibendum.

J. Doe
  • 75
  • 1
  • 1
  • 10
  • Please add several examples like, input line -> expected result – Yuriy Gyerts Apr 25 '23 at 07:37
  • This is how resulting string looks like after using simple `replace` Lorem ipsum dolor sit amet, consectetur adipiscing elit. /nSuspendisse eleifend fringilla ante, eleifend facilisis ne/nque egestas id. Sed ac placerat est, at elementum felis. Donec in /nquam et dolor dictum dignissim ut a quam. Vestibulum id sapien lacus. Donec gr/navida fermentum leo nec pharetra. Suspendisse vitae tempus nulla, et dignissim sem. Vivamus i/npsum massa, aliquet sed finibus in, ullamcorper vel ipsum. Integer porttitor justo id ligula/n pulvinar consequat. D/nonec nunc arcu, feugiat at hendrerit interdum, – J. Doe Apr 25 '23 at 07:37
  • Desired output: Lorem ipsum dolor sit amet , consectetur adipiscing elit. Proin et metus eget massa facilisis ultricies sit amet sit amet mi. Donec in hendrerit justo. Ut ut enim vehicu la metus ullamcorper lacinia sit amet fe ugiat sem. Vivamus t empor eros consequat felis tempus tincidunt. Nullam h endrerit orci dictum dolor volutpat, in maximus lorem imperdiet. Aliquam tristique nunc nec tellus pretium luctus. Nulla suscipit non magna ac bibendum. D – J. Doe Apr 25 '23 at 07:39
  • Well it doesnt show new lines in this comment section here but I need a text that doesn't have backslash symbols but still has all special symbols like \n \r etc. So normal text but all visible backslashes are replaced with forward slashes – J. Doe Apr 25 '23 at 07:40
  • Here is an example https://ideone.com/HJEYPt where the "\n" is not changed. Can you edit your question to include the actual code that produces the errors? – matt Apr 25 '23 at 07:52
  • Take a look here. https://stackoverflow.com/help/minimal-reproducible-example – matt Apr 25 '23 at 07:55
  • @matt I look here https://ideone.com/HJEYPt and this is exactly my code. `replace("\\", "/")` results in broken new line characters – J. Doe Apr 25 '23 at 08:00
  • 1
    Why? What are these backslashes and where do they come from? – user207421 Apr 25 '23 at 08:02
  • @J.Doe In the example I pasted, it works fine. The `\n` does not get broken into two characters with the first one being replaced. It absolutely does not be come "/n" if I use `replace("\\", "/");` You need to create a complete compilable example because the behavior you're witnessing doesn't happen, so it is probably something else. – matt Apr 25 '23 at 08:06
  • What it sounds like is you have `String s = "broken\\nlines";`. Then it *is not a newline character* but two characters "\" and "n". You could `string.replace("\\n", "\n");` and get new lines instead of having two characters that *look like* a newline character. How are you getting the string? – matt Apr 25 '23 at 08:09
  • @matt string comes from a web form (JavaScript). Also I updated my question with an actual code piece from my app – J. Doe Apr 25 '23 at 08:14
  • You can check out this quesiton. https://stackoverflow.com/questions/3537706/how-to-unescape-a-java-string-literal-in-java Which version of java are you using? – matt Apr 25 '23 at 08:29
  • @matt Unfortunately I'm not allowed to modify the core of this app. Existing JSON structure has to stay. Updated question with example/desired string. Java version is 17. Javax Servlet version is 2.4 – J. Doe Apr 25 '23 at 08:35
  • @matt Actual string data comes from a web request. Declaration is ` paramMap = req.getParameterMap(); for (Map.Entry item : paramMap.entrySet()) { for (int i = 0; i < item.getValue().length; i++) { String logString; logString = "[" + item.getKey() + ":" + item.getValue()[i] + "](" + i + ")"; log.info(logString); } }` Maybe I can replace backslash here? – J. Doe Apr 25 '23 at 08:40
  • @matt Are you sure about `translateEscapes`? Doesn't work for me: `Cannot resolve method 'translateEscapes' in 'String'` – J. Doe Apr 25 '23 at 08:46
  • not really sure I understand this right. I need to call `translateEscapes()` on my string variable is this correct? like `someString.translateEscapes()`. Or is it like `var newString = String.translateEscapes(oldString)` ? – J. Doe Apr 25 '23 at 09:02
  • The latter, String is immutable. When you call methods that change the String it returns a new one. – matt Apr 25 '23 at 09:05
  • @matt It didn't work : `[ERROR] symbol: method translateEscapes() [ERROR] location: class java.lang.String` – J. Doe Apr 25 '23 at 09:17
  • Sounds like you're not using jdk 17 to run your servlet. – matt Apr 25 '23 at 09:19
  • @matt how do I know which version am I using? I didn't design this app. Also is there a solution to my problem if it really isn't jdk 17? – J. Doe Apr 25 '23 at 09:23
  • I meantioned above, replace the escaped characters with their actual characters. ie. `s = s.replace("\\n", "\n");` do that first – matt Apr 25 '23 at 09:31
  • You may want to create a few objects or records allowing you to build the structure you need, and then simply just serialize it to JSON. Your current approach is brittle and hard to maintain and debug. – Thorbjørn Ravn Andersen Apr 28 '23 at 23:52

1 Answers1

1
somestring.replaceAll("\\\\(?!n)", "/");
Windir
  • 98
  • 7