So, I got values from DB #Table that contains column with String value and json in it. But as I try to map it with ObjectMapper.writeValueAsString() all i get is this (Also implying that those escape symbols as backward slashes are in a string):
\"list\" [ \"key\":\"value\", ... , \"key\":\"value\"] }
It also appears that #Entity class have other fields as that table columns, but they seem to map okay, without escape symbols inside a String
Any idea why that happens? Thanks in advance
Try
String yourJson = "{Key:\\'aa'}";
String a = yourJson.replace("\\","");
System.out.println(a);
Similar:
unclosed string literal error at compile time because it contains double quotes and pre tags of HTML
Related
I have this column in a MySQL table which has a JSON string and I'm trying to pull records using regex.
For example, the column 'paylod' (datatype long text) holds this value
{
"type":"assignment",
"location":"12345"
}
I'm using RLIKE to fetch records based on location.
select * from table where payload RLIKE '"location":"[[:<:]]12345[[:>:]]"';
When using this query in java, I'm using prepared statement.
String pattern = "\"location\":\"[[:<:]]12345[[:>:]]\""
And when I use preparedStatement.setString(payload, pattern), I'm not getting any results back. But when I execute the query in workbench, I see the rows fetched.
I'm guessing it's because I'm using setString, it is wrapping pattern with double quotes and MySQL is not able to parse it.
So is there a way forward? My requirement is to get records based on key-value pair in the JSOn payload column.
Alright, adding escape character in string helped.
String pattern = "'\"location'\":'\"[[:<:]]12345[[:>:]]'\"";
String patternValue = pattern.replaceAll("'","\\\\");
So the string becomes \"location\":\"[[:<:]]12345[[:>:]]\" where \ serves as escape character for " in mysql, when string is wrapped inside ""
I have field in mongoDb collection "name" which contains:
"26.11.2018(2)"
I use regex expression for searching if any string contains in field "name":
String search = "11.2018(2)";
return Criteria.where("name").regex(search);
I got exception, that regular expression is wrong(because of ")"). Is there any other possibility for searching like this?
You need to escape the value that's used in the regex.
I can't test it now, but it's possible that it may work:
String search = "some pattern(a)12.";
pattern = Pattern.compile(Pattern.quote(search), Pattern.CASE_INSENSITIVE);
return Criteria.where("name").regex(pattern);
https://mongodb.github.io/mongo-java-driver/3.4/javadoc/?com/mongodb/client/model/Filters.html
Is there any way to convert the string below to a list?
This string is retrieved after scanning a QR code.
CashRequest{
orderid='0',
user_id='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
userName='username',
userEmail='whateveremailthisis#email.blabla',
fullName='full name',
phoneNumber=0,
totalCash='$304.00',
totalRV='$34.00',
foods=[
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='-LMDiT7klgoXU8bQEM-4',
ProductName='Coke',
Quantity='4',
Price='1',
RedemptionPrice='10',
RedemptionValue='1'},
Order{
userID='nvHt2U5RnqUwXB4ZK37Zn1DXPV82',
ProductID='1000',
ProductName='Kunau Ring Ring Pradu',
Quantity='3',
Price='100',
RedemptionPrice='10',
RedemptionValue='10'
}
]
}
The desired output is to store it in firebase realtime database as below :
Well you have a few options. Since it is newline between values, you could use simple newline reads and compare if it starts with "reserved word that you are looking for" then substring from there, but that can get messy and a lot of bloat code.
The simplest way would be to do the known replace first.
Make a method that replaces all bad json keys with quote surrounded json keys like:
val myJsonCorrected = yourStringAbove.replace("Order", "\"Order"\")
repeat for all known entities until you have made it into valid json. Single ticks are fine for the values, but the keys need quotes as well.
Then simply create an object that matches the json format.
class CashRequestModel{
#SerializableName("orderid")
var orderID: Int? = null
etc.....
#SerializableName("foods")
var myFoods: ArrayList<OrderModel>? = null
}
class OrderMode {
#SerializableName("userID")
var userID: String? = null
#SerializableName("ProductID")
var userID: String? = null
etc..
}
Then simply convert it to JSON
val cashRequest = getGson().fromJson(cleanedUpJson, classTypeForCashRequest);
and your done. Now just use the list. Of course it would be better if you could get valid JSON without having to clean it up first, but it looks like the keys are known and you can easily code string replaces to fix the bad json before casting it to object that matches the structure.
Hope that helps.
I have the following code where I can't seem to figure out how to escape the single quotes around my named parameter. In the resulting query, I need to have single quotes on either side of it:
public List<Vehicle> findByApplicationId(String applicationId) {
// example application id is a string like 12345
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
sqlParameterSource.addValue("applicationId", applicationId);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("SELECT make, model");
stringBuilder.append(" FROM vehicle");
stringBuilder.append(" WHERE model IN (SELECT id FROM auto WHERE model_app IN (");
stringBuilder.append(":applicationId");
stringBuilder.append("))");
// in the resulting query the applicationId must appear
// as '12345', meaning with single quotes around it
return jdbcTemplate.query(stringBuilder.toString(), sqlParameterSource,
// lambda used as row mapper
(resultSet, rowNumber) -> {...
...
I've tried to put double single quotes around the name parameter as in stringBuilder.append("'':applicationId''");, that didn't work. I tried single single quotes and many other such combinations of single and double quotes based on other answers I've seen on SO. Can't seem to get it.
Turns out my problem wasn't single quotes at all as suggest by Alex Poole (thank you Alex). It was that my Java string needed to be cast to the Oracle type CHAR(17). After I did that no quotes, single or double, were necessary and my named parameters resolved correctly and the query worked.
สวัสดี Mr.Java Sp'e c'i'a'l'' '
I tried to parse the String using below code but I could't make
simply it shows the wrong value.
String s = "สวัสดี Mr.Java Sp'e c'i'a'l'' '"";
s = s.replaceAll("'", "'");
//s = s.replaceAll("'", "''");
StringEscapeUtils.escapeHtml(s);
I am trying to get from JSP and save in SQL Server DB and show using JSP and update.
But some times in JSP it shows the converted &apos in jsp as it is instead of Special
Chars.
Very Simple is Here I have shown this String(สวัสดี Mr.Java Sp'e c'i'a'l'' ') in StackOverflow they
save in their DB and Shows and allows me to update this is what I
wanted.
OK. So lets look at what your code does:
// line 1
String s = "สวัสดี Mr.Java Sp'e c'i'a'l'' '";
We have a String with various international characters in it ... and some "'" characters.
// line 2
s = s.replaceAll("'", "'");
Assuming that those are really "'" characters characters, we will replace all instances of "'" with an XML / HTML character entity giving us:
"สวัสดี Mr.Java Sp'e c'i'a'l'' '"
And so ...
// line 3
s = StringEscapeUtils.escapeHtml(s);
This replaces any active HTML / XML characters with character references. This includes the ampersand characters "&" that you previously inserted. The result is this:
"&#xxxx;&#xxxx;&#xxxx;&#xxxx; Mr.Java Sp'e
c'i'a'l'' '"
(The &#xxxx; numeric character references encode those Thai (?) characters.)
When you embed that in an HTML document and display it, you will see "สวัสดี Mr.Java Sp'e c'i'a'l'' '"
See what has happened? You have HTML escaped your HTML escaped apostrophies!!
So what do you really need to do?
There is no need replace apostrophes with '. Apostrophes are legal in HTML text.
There should be no need to add HTML escapes so that you can store text in a database:
Any modern database will allow you to store Unicode strings without any special encoding.
If you are trying to prevent the database's SQL parser getting confused by quotes in the text you are storing, you are doing it the wrong way. The right way to do this is to use a PreparedStatement, add parameter placeholders to the query, and use the PreparedStatement.setXxx methods to provide the parameter values. The execute (or whatever) will take care of any SQL escaping that needs to be done.