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).
Related
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.
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.
I need to send a request to a RESTful Service which contains the '≈' special character.
The Request Body should look like this:
{
"searchText":"Pipe ≈ 1,25d"
}
The '≈' symbol is not included in UTF-8 encoding.
In case you know how to pack this character in a Java String, please let me know.
Being able to type it depends on your keyboard and setup. You can, however, copy/paste strings into Java source.
String s = "Pipe ≈ 1,25d";
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)'";
The application I support is going through security review and there are some questions regarding escaping special characters. I have not been supporting this application for a long time and I'm not very knowledgeable about escaping special characters. The question I was asked is "Why are you JavaScript encoding the value and then HTML encoding it? Is that value written out in a context that requires the value to be encoded for both contexts?"
What is the difference between JavaScript encoding used and HTML encoding used? Why would I need both in my code?
Any information regarding this will be greatly appreciated!
public class HTMLEncodedResultSet extends ResultSetWrapper {
public HTMLEncodedResultSet(ResultSet resultSet) {
super(resultSet);
}
public String getString(int columnIndex) throws SQLException {
return StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(super.getString(columnIndex)));
}
public String getString(String columnName) throws SQLException {
return StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(super.getString(columnName)));
}
}
From the official documentation:
escapeHtml
Escapes the characters in a String using HTML entities.
For example:
"bread" & "butter"
becomes: "bread" & "butter".
escapeJavaScript
Escapes the characters in a String using JavaScript String rules.
Escapes any values it finds into their JavaScript String form. Deals
correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
So a tab becomes the characters '\' and 't'.
Example:
input string: He didn't say, "Stop!" output string: He didn\'t say,
\"Stop!\"
So, given that JS and HTML reserved characters are not the same, in your case if the input has HTML and JS code it may be necessary to invoke both methods.
It looks like that your application has JavaScript snippets stored in database. These snippets might create or contain HTML parts (i.e. for generating dynamic HTML based on interaction). When loading these snippets from DB as a string in Java a JavaScript AND HTML encoding is required.
Here an example of a value that could be stored in DB.
var obj = $('#fire');
var fps = 200;
var letters = obj.html().split('');
obj.empty();
$.each(letters,function(el){
obj.append($('<span>'+this+'</span>'));
});
var animateLetters = obj.find('span');
setInterval(function(){
animateLetters.each(function(){
$(this).css('fontSize', 80+(Math.floor(Math.random()*50)));
});
},fps);
Referring to the documentation:
escapeHTML: Escapes the characters in a String using HTML entities.
For example:
"bread" & "butter"
becomes: "bread" & "butter".
and
escapeJavaScript: Escapes any values it finds into their JavaScript
String form. Deals correctly with quotes and control-chars (tab,
backslash, cr, ff, etc.)
So a tab becomes the characters '\' and 't'.
The only difference between Java strings and JavaScript strings is
that in JavaScript, a single quote must be escaped.
Example:
input string: He didn't say, "Stop!" output string: He didn\'t say,
\"Stop!\"