Home > Net >  Remove \n l special characters from JSON String
Remove \n l special characters from JSON String

Time:07-11

I am receiving a json like "{\n \"brand\" : \"BMW\",\n \"model\":\"X7\" \n}"

However, I want to remove those escape characters and want to have the JSON like

 { "brand":"BMW", "model":"X7"}

I am using the below snippet to remove the characters from the json string.

String response = jsonString.replace("\\\n","").replace("\\","");

output for the above is

{n "brand":"BMW",n "model":"X7" n}

Not sure how to achieve my result.

CodePudding user response:

When you do .replace("\\\n",""), it doesn’t replace anything because the string representation of \\\n doesn’t exist in your string.

When you do .replace("\\",""), you’re trying to replace a single \ which exists and therefore you’re left with the single n in your string.

For your string, you’ll need:

jsonString
    .replace("\\n", "")
    .replace("\\", "");

First to replace all \n and second to remove all \.

But this is a naive implementation and could lead to problems. For e.g., what if your key or value in the json response contains \? You will no longer have the original response.


A better solution would be to use a library like org.json or json.simple to parse json responses you receive which will handle all the escaping for you.

CodePudding user response:

The following code should work as expected:

String response = jsonString.replaceAll("[\\n\\t ]", "");

This will remove all newlines, spaces and tab characters from a string.

CodePudding user response:

There 2 separate things needs to be addressed here, the escape chars \" and the line separator \n.

  1. In java, \" is esacpe chars for json String when inputing Strings. When you say you are 'receiving' it with it, what do you mean? Java will parse a string with the escape chars into a valid json. Only if you are manually inserting the json yourself you need to add the escape chars. All that is to say, that the \" in your json are perfectly valid. Dont take my word for it, just print your json and you will see:

    System.out.println("{\"brand\":\"BMW\",\"model\":\"X7\"}");
    

Will give:

{ "brand":"BMW", "model":"X7"}
  1. The line seperator \n is probably there because someone sent you the json in the formatted form. You can just remove it if you want to flatten your json, but it will still be a valid json with it. String s2 = response.replaceAll(System.getProperty("line.separator"), ""); System.out.println(s2);

output:

{ "brand" : "BMW",   "model":"X7" }
  • Related