I'm using the Gson library for this. But it looks like this is what you are asking for.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
...
public void stuff()
    {
        List<String> data = new ArrayList<String>();
        data.add("");
        data.add("abc");
        data.add("IF(Var218 = \"charlie\") AND (Var85 &le; 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ");
        data.add("\"\"");

        Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();

        JsonObject test = new JsonObject();
        JsonElement jsonData = gson.toJsonTree(data, new TypeToken<List<String>>(){}.getType());
        test.add("test", jsonData);

        String json = gson.toJson(test);
        System.out.println(json);
    }

This will produce:

{
  "test":[
    "",
    "abc",
    "IF(Var218 = \"charlie\") AND (Var85 &le; 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
    "",
    "\"\""
  ]
}
Answer from Nick Allen on Stack Overflow
🌐
JSON Formatter
jsonformatter.org › json-escape
Best JSON Escape Characters, Double Quotes and Backslash tool
Backspace is replaced with \b, Form feed is replaced with \f, Newline is replaced with \n, Carriage return is replaced with \r, Tab is replaced with \t, Double quote is replaced with \", Backslash is replaced with \\. JSON Escape is an essential ...
🌐
Reddit
reddit.com › r/javahelp › escape double-quotes in json string
r/javahelp on Reddit: Escape double-quotes in JSON string
September 29, 2021 -

I have an input string as below:

"key":"Life Goes "ON""

I need to create a JSONObject which uses the below:

String val ={\"key\":\"Live Goes \"ON\"\"}; 
net.sf.json.JSONObject obj = net.sf.json.JSONObject.fromObject(" + val + ");

The above code throws a JSONException as it finds double quotes inside the value:

net.sf.json.JSONException:at net.sf.json.util.JSONTokener.syntaxError(JSONTokener.java:505)at net.sf.json.JSONObject._fromJSONTokener(JSONObject.java:1271)at net.sf.json.JSONObject._fromString(JSONObject.java:1373)at net.sf.json.JSONObject.fromObject(JSONObject.java:161)at net.sf.json.JSONObject.fromObject(JSONObject.java:130)

Could any let me know if we can escape the inner double quotes before fromObject method call?

I thought of doing as below:

String[] values  =  val.split(":");
JSONObject obj = new JSONObject();
obj.put(values[0].substring(1, values[0].length() - 1), values[1].substring(1, values[1].length() - 1).replace("\"", "\\\""));

Is there any better way to do this?

Top answer
1 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 2
1
That is invalid json and as such, cannot be parsed. The string should have been escaped in the Json already.
Discussions

[SOLVED] How to escape double quotes from jsonpath string?
All, I would like to extract OK from the following response: {“status”:“OK”,“statustext”:“Switching the screen off”} But I fail. I found a very helpful site to check some approaches, but did not succeed. https://jso… More on community.openhab.org
🌐 community.openhab.org
1
0
October 3, 2017
Is there a way to automatically escape quotes in Java String using Gson
This is my sample code: ` class SampleObject { String field; public SampleObject() { field = "Great 'news'"; } public String getField() { return field; } } · private static class EscapeStringSerializer implements JsonSerializer { @OverRide public JsonElement serialize(String s, Type type, ... More on github.com
🌐 github.com
6
September 17, 2021
How to escape double quotes in JSON - Stack Overflow
If it includes all three, it uses double quotes and escape the double quotes. 2023-02-28T21:49:51.043Z+00:00 ... If you're inside javascript, python, etc., use raw strings (python's r'' or javascript's String.raw or similar). They make it much easier to write JSON strings because they avoid ... More on stackoverflow.com
🌐 stackoverflow.com
Regex to escape double quote in a Json Value in Java - Stack Overflow
I have a JSON string which might have unescaped double quotes characters in the JSON value part. I am trying to capture them using regex and escape using java.util.regex.Matcher and later convert the More on stackoverflow.com
🌐 stackoverflow.com
August 25, 2019
🌐
FreeFormatter
freeformatter.com › json-escape.html
Free Online JSON Escape / Unescape Tool - FreeFormatter.com
The following characters are reserved in JSON and must be properly escaped to be used in strings: Backspace is replaced with \b · Form feed is replaced with \f · Newline is replaced with \n · Carriage return is replaced with \r · Tab is replaced with \t · Double quote is replaced with \" ...
🌐
openHAB Community
community.openhab.org › setup, configuration and use › scripts & rules
[SOLVED] How to escape double quotes from jsonpath string? - Scripts & Rules - openHAB Community
October 3, 2017 - All, I would like to extract OK from the following response: {“status”:“OK”,“statustext”:“Switching the screen off”} But I fail. I found a very helpful site to check some approaches, but did not succeed. https://jsonpath.curiousconcept.com/ With val String response = transform("JSONPATH", "$.status", json) the website above returns “OK”. Actually I have two issues: I would like to get OK instead of “OK” When I run the website from a browser, I get the response mentioned above: {...
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - The simplest and smallest library in our review is JSON-java also known as org.json. To construct a JSON object, we simply create an instance of JSONObject and basically treat it like a Map: JSONObject jsonObject = new JSONObject(); jsonObject.put("message", "Hello \"World\""); String payload = jsonObject.toString(); This will take the quotes around “World” and escape them:
🌐
Java Code Geeks
javacodegeeks.com › home › core java
How to Escape JSON String in Java - Eclipse IDE Tips - Java Code Geeks
June 27, 2017 - You can escape String in Java by putting a backslash in double quotes e.g.” can be escaped as\” if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quotes with escape character for even ...
🌐
Coderanch
coderanch.com › t › 702023 › java › Include-Double-Quote-JSON-String
Include Double Quote in JSON String (Java in General forum at Coderanch)
November 10, 2018 - JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility ... OK, now I'm confused. Why exactly are you trying to turn the escaped quotes in this String into two lots of double quotes? That will not fix the broken Json.
Find elsewhere
🌐
GitHub
github.com › google › gson › issues › 1970
Is there a way to automatically escape quotes in Java String using Gson · Issue #1970 · google/gson
September 17, 2021 - Is there a way to automatically escape quotes in Java String using Gson#1970 · Copy link · venkatmandavilli · opened · on Sep 17, 2021 · Issue body actions · This is my sample code: ` class SampleObject { String field; public SampleObject() { field = "Great 'news'"; } public String getField() { return field; } } private static class EscapeStringSerializer implements JsonSerializer { @OverRide public JsonElement serialize(String s, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(escapeSpecialChar(s)); } public static String escapeSpecialChar(String
Author   venkatmandavilli
🌐
Blogger
javarevisited.blogspot.com › 2017 › 06 › how-to-escape-json-string-in-java-eclipse-IDE.html
How to Escape JSON String in Java- Eclipse IDE Tips and Example
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even ...
🌐
CodingTechRoom
codingtechroom.com › question › how-to-escape-quotes-in-json-object
How to Properly Escape Quotes in a JSON Object - CodingTechRoom
Solution: Always use a backslash to escape internal double quotes. Mistake: Mixing single and double quotes incorrectly. Solution: Stick to one type of quotation (double quotes) for JSON attributes. ... Learn how to fix the METAINFpersistence.xml was not found error in Gradle projects with ...
Top answer
1 of 11
774

Try this:

"maingame": {
  "day1": {
    "text1": "Tag 1",
     "text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
  }
}

(just one backslash (\) in front of quotes).

2 of 11
75

When and where to use \\\" instead. OK if you are like me you will feel just as silly as I did when I realized what I was doing after I found this thread.

If you're making a .json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes:\" is the one you're looking for.

However if you're like me and you're trying to get the w3schools.com "Tryit Editor" to have a double quotes in the output of the JSON.parse(text), then the one you're looking for is the triple backslash double quotes \\\". This is because you're building your text string within an HTML <script> block, and the first double backslash inserts a single backslash into the string variable then the following backslash double quote inserts the double quote into the string so that the resulting script string contains the \" from the standard answer and the JSON parser will parse this as just the double quotes.

<script>
  var text="{";
  text += '"quip":"\\\"If nobody is listening, then you\'re likely talking to the wrong audience.\\\""';
  text += "}";
  var obj=JSON.parse(text);
</script>

+1: since it's a JavaScript text string, a double backslash double quote \\" would work too; because the double quote does not need escaped within a single quoted string eg '\"' and '"' result in the same JS string.

Top answer
1 of 2
1

If this value string;

str = str.replaceAll("\/","");

Make "/" change ""(EMPTY).

or

try {
     FileReader reader = new FileReader("JSON file path");
     JSONParser jsonParser = new JSONParser();
     String jsonString = jsonParser.parse(reader).toString();
} catch (Exception e) {
     e.printStackTrace();
}

For JSONParser

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
2 of 2
1

For the example data, you could match the key part and in the value part make use of \G to get repetitive matches asserting the position at the end of the previous match.

To make sure there is at least an opening and a closing curly brace you could make use of lookarounds. Java does not support infinite lookbehind, but is does support finite lookbehind by specifying a number for the quantifier.

In this example a I have chosen {0,1000} but you can of course change that to your requirement.

(?<=\\{[^\\{}]{0,1000})("[^\r\n"{}]+":\s*"|\G(?!^))([^"\r\n{}]*)(")(?=[^{}]*})(?!\s*(?:,|$))

In Java

final String regex = "(?<=\\{[^\\{}]{0,1000})(\"[^\\r\\n\"\\{}]+\":\\s*\"|\\G(?!^))([^\"\\r\\n\\{}]*)(\")(?=[^\\{}]*\\})(?!\\s*(?:,|$))";

In the replacement use the 3 capturing groups:

String subst = "$1$2\\\\$3";

Java demo

Pattern parts

  • (?<= Finite positive lookbehind, assert what is on the left is
    • {[^{}]{0,1000} Match { followed by 0 - 1000 times not { or }
  • ) Close lookbehind
  • ( Capturing group 1
    • "[^\r\n"{}]+" Match ", 1+ any char except what is in the character class
    • :\s*" Match :, 0+ whitespace chars
    • | Or
    • \G(?!^) Assert position at the end of previous match
  • ) Close group
  • ([^"\r\n{}]*) Capture group 2, match 0+ times any char except the listed
  • (") Capture group 3, match "
  • (?= Positive lookahead, assert what is on the right is
    • [^{}]*} Match 0+ times any char except the listed, then match }
  • ) Close lookahead
  • (?! Negative lookahead, assert what is on the right is not
    • \s*(?:,|$) Match 0+ times a whitespace char, then match either , or end of the string
  • ) Close lookahead

Result

{
  "DESC1":"Steve\"s and Carl\"s \" Car",
  "DESC2": "Steve's and Carl\"s Car",
  "DESC3": "\"",
  "DESC4": "Steve and Carl"
}
🌐
Testmuai
testmuai.com › home › free tools › json escape
JSON Escape Free Online | Free online tool to convert plain JSON content to escaped HTML.
To escape double quotes in JSON, use a backslash () before the double quote like this: " Your text here ". how to remove escape character from json string in java
🌐
Claris Community
community.claris.com › en › s › question › 0D53w00005PrPSyCAN › how-to-allow-quote-in-json-value
how to allow quote in json value - Claris Community
July 20, 2021 - While ( [ LST = "¶Ford¶¶BMW¶te\"\"st" ; QTY = ValueCount ( LST ) ; i = 0 ; r = "[]" ] ; i < QTY ; [ i = i + 1 ; r = JSONSetElement ( r ; [ i - 1 ; GetValue ( LST ; i ) ; JSONString ] ) ] ; r ) // ==> ["","Ford","","BMW","te\"\"st"] ... Thank you. I have FMP 17. So While is out. ... FMListToJSONArrayCF ( key , fmList )Let ( [ fmlist = quote ( fmlist ) ; fmlist = middle ( fmlist , 2 , length ( fmlist ) - 2 ) ; fmList = "[\"" & Substitute ( fmList ; "\¶" , "\",\"" ) & "\"]" ] , if ( isempty ( key ) , fmlist , "{" & quote ( key ) & ":" & fmlist & "}" ) )
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-escape-double-quotes-in-json
How to Escape Double Quotes in JSON? - GeeksforGeeks
September 24, 2024 - The most common and straightforward method to escape double quotes in JSON is by using the backslash (\) character. This allows us to include double quotes within the value of a string without confusing the JSON parser.
🌐
Stack Overflow
stackoverflow.com › questions › 54482774 › how-to-escape-double-quotes-in-a-json-in-java-dynamically
How to escape double quotes in a JSON in Java dynamically - Stack Overflow
February 1, 2019 - If a user enters I am a new "user" and you use @Adam 's solution you will end with I am a new \"user\" and the String will be escaped correctly ... You could find a library for this specific use case if you're lucky. But it's much easier to just write it yourself as @VictorCalatramas suggested as it's a trivial solution. if you want to only escape quotes around URLs that's a bit more involved as you'll need to do some regex matching.
🌐
Java2Blog
java2blog.com › home › core java › string › how to escape double quotes in string in java
How to escape double quotes in String in java - Java2Blog
October 18, 2021 - Some IDEs like intelij automatically escape String if you paste the String between double quotes surrounding the String literal. If you want to add double quotes(") to String, then you can use String’s replace() method to replace double quote(") ...