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 ≤ 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 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
"",
"\"\""
]
}
Answer from Nick Allen on Stack OverflowI 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?
[SOLVED] How to escape double quotes from jsonpath string?
Is there a way to automatically escape quotes in Java String using Gson
How to escape double quotes in JSON - Stack Overflow
Regex to escape double quote in a Json Value in Java - Stack Overflow
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 ≤ 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 ≤ 0) AND (Var207 = \"some value\"; \"du\") THEN Appetency = 1 ",
"",
"\"\""
]
}
In java you escape " by \" and the same goes for JSON. The problem is that \" does not include a backward slash, so you need to escape that as well:
String json = "hello \\\"world\\\""; // hello "world"
Notice the three (3) backwards slash.
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).
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.
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>
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"
}