-5

I have a JSON response where all the double quotes are delimited with \. So to print contents as JSON format, I need to replace \" with ".

I'm using Java's string replaceAll method to do so, but couldn't achieve the same.

Something like below to get replace \" with "

String name ="{
  id: 1,
  name: "Leanne Graham",
  username: "Bret",
  email: "Sincere@april.biz",
  address: {
    street: "Kulas Light",
    suite: "Apt. 556",
    city: "Gwenborough",
    zipcode: "92998-3874",
    geo: {
      lat: \"-37.3159\",
      lng: \"81.1496\"
    }";

name.replaceAll("\"",""");
Sentry
  • 4,102
  • 2
  • 30
  • 38
Giri
  • 411
  • 2
  • 18
  • 4
    Not sure if you know this already but, on printing the string `name`, no slashes will be printed. The backslash in `name` are called *escape character*. It is used to tell JVM "Okay, the following quote is not the ending quote for the string." – joker Aug 18 '18 at 11:33
  • modified the code, could you refer now. sorry for the confusion – Giri Aug 18 '18 at 11:40
  • 5
    The string is nothing but a syntax error – baao Aug 18 '18 at 11:40
  • You cannot split string definition into multiple lines unless you add a backlash at the end of each line you want to use the following one. Meaning, there should a backslash here `name = "{\ ` and here `id: 1,\ `, etc. – joker Aug 18 '18 at 11:43

1 Answers1

0

At first your json format is wrong, there are two missing }, because of the address and the main objects.

Also your shown java code is wrong, because of missing escapes. The following code will compile and should do what you expect:

de/test/Test.java

package de.tests;

public class Test
 {
  public static void main(final String[] args)
   {
    final String name = "{id: 1,  name: \"Leanne Graham\",  username: \"Bret\",  email: \"Sincere@april.biz\",  address: {  street: \"Kulas Light\",  suite: \"Apt. 556\",  city: \"Gwenborough\",  zipcode: \"92998-3874\",  geo: {lat: \\\"-37.3159\\\", lng: \\\"81.1496\\\"}}}";

    // System.out.println(name);
    System.out.println(name.replaceAll("\\\\\"","\""));
   }
 }

The important point here is the regular expressin escaping, because you have different layers for which you need the escaping - the first one is the java source code itself, the second one is the json string - so you need a double escaping.

For more on regular expressions please read something like Mastering regular expressins

PowerStat
  • 3,757
  • 8
  • 32
  • 57