Gson adding backslash in String - java

I am having user defined object Customer which has multiple attributes ,in one of the attributes we can have single , double quotes and backslash as well. While converting the object to string Gson library is adding backslash in it.
I am using below code to achive this but it is not working.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
JsonElement jsonString = gson.toJsonTree(triggerModel);
Output is
{
"customerId": "1234",
"customerName": "Loren",
"customerAddress": [
{
"postalcode": "67676",
"lane": "\"LA16767",
"houseNumber": "2025",
"society": "null"
}
]
}
In lane attribute the original value was "LA16767 but it is adding one backslash character. How to write this in such a way string with single ,double quotes and backslash are handled using same line of code.

Output provided by Gson is correct because "lane": ""LA16767" would not have been a valid json.
From json docs
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
You had mentioned :
How to write this in such a way string with single ,double quotes and backslash are handled using same line of code.
You need not do anything special to handle single ,double quotes and backslash characters. Gson will automatically escape them for you.
Any app (server, UI, etc,) who is consuming your json, will correctly parse "\"LA16767" as "LA16767 going by the json conventions.

Related

How to convert utf8 string to escape string in JSON Java?

I want to convert a UTF-8 string to escape \uXXX format in value of JSON Object.
I used both JSON Object and Gson, but did not work for me in this case:
JSONObject js = new JSONObject();
js.put("lastReason","nguyễn");
System.out.println(js.toString());
and
Gson gson = new Gson();
String new_js = gson.toJson(js.toString());
System.out.println(new_js);
Output: {"test":"nguyễn"}
But i am expect that my result is:
Expected Output: {"test":"nguy\u1EC5n"}
Any solutions for this case, please help me to resolve it.
You can use apache commons-text library to change a string to use Unicode escape sequences. Use org.apache.commons.text.StringEscapeUtils to translate the text before adding it to JSONObject.
StringEscapeUtils.escapeJava("nguyễn")
will produce
nguy\u1EC5n
One possible problem with using StringEscapeUtils might be that it will escape control characters as well. If there is a tab character at the end of the string it will be translated to \t. I.e.:
StringEscapeUtils.escapeJava("nguyễn\t")
will produce an incorrect string:
nguy\u1EC5n\t
You can use org.apache.commons.text.translate.UnicodeEscaper to get around this but it will translate every character in the string to a Unicode escape sequence. I.e.:
UnicodeEscaper ue = new UnicodeEscaper();
ue.translate(rawString);
will produce
\u006E\u0067\u0075\u0079\u1EC5\u006E
or
\u006E\u0067\u0075\u0079\u1EC5\u006E\u0009
Whether it is a problem or not is up to you to decide.

How to escape or remove "\" from the gson generated string?

I am loading a value from the property file and then passing it to gson method for converting it to final json object. However, the value coming from the property file has double quotes for which the gson is adding "\" to the output. I have scanned down the whole web but unable to find a solution
The property file contains
0110= This is a test for the renewal and the "Renewal no:"
Here's my code
public String toJSONString(Object object) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
//Note object here is the value from the property file
return gson.toJson(object);
}
This produces
"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
I am not sure in the output, why it is adding or wrapping the \ around the literals or where ever we have the double quotes in the property file value?
Based on comments on your question, the object parameter is actually referencing a Java String with the value
{ResponseCode:0110,ResponseText:This is a test for the renewal and the "Renewal no:"}
I can't say why, but that's what your String contains.
String is a special type which Gson interprets as a JSON string. Since " is a special character that must be escaped in JSON strings, that's what Gson does and produces the JSON string.
"{ResponseCode:0110,ResponseText:This is a test for the renewal and the \"Renewal no:\"}"
The \ character is escaping special characters like " in the string. You can't store a " in a string without a leading . It has to be \".
You remove the slashes when you display any output string.
Apache Commons has a library for handling escaping and unescaping strings: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Store Backward slash and forward slash in java string

I am parsing below string value into OData query through java code.
objects.put("EndDate", "\/Date(1441756800)\/";
How can i parse the /Date(1441756800)/ into a string in java.
I have tried with below :
objects.put("EndDate", ""\\""//"Date(1441756800)""\\""//"";
throws error:(
I never used OData so I may not understand your question correctly, but if you are asking how to write \/Date(1441756800)\/ as String then you need to escape \ as it is String special character (used for instance when escaping or when creating other special characters like line separators \n).
So try with "\\/Date(1441756800)\\/"
Try this - objects.put("EndDate", "'Date(1441756800)'";

Java Spring: Web Service REST producing double backslash at JSON

So i have this String e.g.
"B\z#b#s#rB{FpMgBrD~DK|"
But Spring is producing this at json:
"B\\z#b#s#rB{FpMgBrD~DK|"
And it's the same with any string that has a backslash \. Replacing the character before generating the json is useless, since the String is correct before the json is generated.
Every client that consumes the service could .replace("\\","\\\\") the json, but I wonder if there will be a cleaner way to solve the problema and at server side.
Here is the code for the WS:
#RequestMapping(value = "/rest/sinc/{ms}", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
#ResponseBody
public String sincronizar(#PathVariable("ms") Long ms) {
return sincService.getSinc(ms).toString();
}
I have tried other ways to generate the json with libraries like Gson but the result is the same.
That is the expected behavior in JSON. \ needs to be escaped. See the specification, here.
All Unicode characters may be placed within the quotation marks,
except for the characters that must be escaped: quotation mark,
reverse solidus, and the control characters (U+0000 through U+001F).

how to make Json lib generate such string: \/Date(1317375052044)\/

My target is to generate such json string: {"EndTime": "\/Date(1309737600000)\/"}
I define a HashMap to generate the string
If I define the string value as "\\/Date(1317375052044)\\/" then the result is "\\\\/Date(1317375052044)\\\\/".
If I define the string as "/Date(1317375052044)/" then the result is "/Date(1317375052044)/".
How I can generate the result "\/Date(1309737600000)\/"?
Duplicated from How should I escape strings in JSON? . Following this response try defining the string as "\\\\/Date(1317375052044)\\\\/" because in Java String '\' is also a escape character!

Categories

Resources