How to avoid the ‘\’ when appying JSONObject.put operation of two strings to a JSONObject?

StackOverflow https://stackoverflow.com/questions/22421021

  •  15-06-2023
  •  | 
  •  

Question

The codes is like the following:

JSONObject solution = new JSONObject(); 
variableName = "TEST"                   
System.err.println("1:"+value);
solution.put(variableName, value);
System.err.println("2:"+solution);

Here is the output result:

1:{"min":10,"max":40}
2:{"TEST":"{\"min\":10,\"max\":40}"}

How can I get rid of the annoying '\'? Thank you very much!

Was it helpful?

Solution

The reason why you are getting \ in your print line is because it is escaping the " character which is used in value. There's nothing wrong with this, it simply signifies that \" is not terminating the string and is instead a value part of that string.

Usage of double quotations is valid JSON, not single quotes - see related Q here.

But if you really want to, if you create value like this:

    JSONObject value = new JSONObject("{'min':10,'max':40}");       

Then you should get the desired output from your existing code:

1:{"min":10,"max":40}
2:{"TEST":{"min":10,"max":40}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top