Encoding a QString in JSON - qt

I'm trying to encode a QString into a JSON string, so that I can inject it safely via QWebFrame::evaluateJavaScript(QString("o.text = %1;").arg(???)).
For example, in php using the function json_encode
echo json_encode('HELLO "me"');
The output would be
"HELLO \"me\""
This is the internal representation of the string, within the Json object.
In the same way, using Qt, how can I retrieve the internal representation of a string, as it would be encoded as a value, within a Json formatted string?

It's really not that difficult. Start by building up the structure with QJsonObjects
QJsonObject obj;
obj.insert("tag1", QString("Some text"));
Then use QDocument to get a string in Json format
QJsonDocument doc(obj);
QByteArray data = doc.toJson(QJsonDocument::Compact);
QString jsonString(data);
This will produce a string, in the form of: -
{ "tag1" : "Some Text" }
Separate items into a list, splitting on ':'
QStringList items = jsonString.split(':', QString::SkipEmptyParts);
There should be 2 items in the list, the second being the value section of the Json string
"Some Test"}
Remove the final '}'
QString value = items[1].remove('}');
Of-course, you will need to do error checking and be aware that if you have a ':' or '}' in the original string, then you'll need to check for them first.

Original answer doesn't handle : and } inside of string correctly. A similar approach using array which requires only stripping []:
QString encodeJsonStringLiteral(const QString &value)
{
return QString(
QJsonDocument(
QJsonArray() << value
).toJson(QJsonDocument::Compact)
).mid(1).chopped(1);
}
ab"c'd becomes "ab\"c'd"
Or, if you don't need double quotes around the string, replace with .mid(2).chopped(2)

Related

Need to change an element of a multidimensional string vector in C++

I have a multidimensional string vector, gameState. The contents of gameState can be seen below. I would like to "move" A up one space by making [2][1] = " " and [1][1] = "A". But I'm getting an error (error: invalid conversion from 'const char*' to '__gnu_cxx::__alloc_traitsstd::allocator<char, char>::value_type' {aka 'char'} [-fpermissive]). Not sure if there is a way to use vector.at() in this case. Here is a snippet. The full code reads in the initial game state from a text file and assigns it to the string vector gameState. I get the row and col indexes for each letter in the grid below and assign them to variables (eg. Arow and Acol). I'm very new to C++, so any help would be appreciated. If you have any questions about the rest of the code, I'd be happy to elaborate. Thanks in advance.
int Arow;
int Acol;
vector<string> gameState;
string tempU = gameState[Arow-1][Acol];
if (tempU != "#") {
// if no wall is up, move up
gameState[Arow][Acol] = " ";
gameState[Arow-1][Acol] = "A";
Arow = Arow-1;
Amovesequence.push_back("U");
}
###########
#...#P...B#
#A#.$.###*#
#...#D...R#
###########
The type of gameState[Arow-1][Acol] is a char, not a string. Modify the code accordingly, e.g.: char tempU = ... and replace " " with ' 'etc.

Use Replace function to remove "{ characters from string

I would like to remove "{ and replace it with {. The following is the line of code that I'm currently using.
var MyString = DataString.Replace(#""{", "");
The following is the error message I'm getting
Please advise
Thanks
You need to escape the quote that you want to replace using two quotes, so for your example:
var MyString = DataString.Replace(#"""{", "{");
Also see How to include quotes in a string for alternatives to use quotes in strings.
If you are expecting JSON data then what you really need is a JSON Parser for that. And if you just want to replace "{ to { then you simply need to escape and replace the string like below:
// Suppose the variable named str has a value of Hello"{ wrapped in double quotes
var strReplaced = str.Replace("\"{", "{");
Console.WriteLine($"strReplaced: {strReplaced}");
// This will result in strReplaced: Hello{

Qt, QUrl, QUrlQuery: Encoding special character in a query string

I create a URL query like this:
QString normalize(QString text)
{
text.replace("%", "%25");
text.replace("#", "%40");
text.replace("‘", "%27");
text.replace("&", "%26");
text.replace("“", "%22");
text.replace("’", "%27");
text.replace(",", "%2C");
text.replace(" ", "%20");
return text;
}
QString key = "usermail";
QString value = "aemail#gmail.com";
QUrlQuery qurlqr;
qurlqr.addQueryItem(normalize(key), normalize(value));
QString result = qurlqr.toString();
The result that's be expecting is :
usermail=aemail%40gmail.com.
But I received:
usermail=aemail#gmail.com
I don't know why. Can you help me?
(I'm using Qt5 on Win7)
QUrlQuery's toString by default decodes the percent encoding. If you want the encoded version try:
qurlqr.toString(QUrl::FullyEncoded)
Also you don't need to manually encode the string by replacing characters; you could instead use QUrl::toEncoded() (I suggest you read the QUrlQuery documentation).

Newtonsoft.JSON error with text with HTML encoded character

I allow user input from TinyMCE on client and store it as a JSON string, then pass it to server ASP.NET C#.
The JSON String looks like this: { "mcfn2" : ";lt;p;gt;Trước đ& oacute;, việc tung ra t& ecirc;n miền lần đầu ti& ecirc;n được sự đồng & yacute; của ICANN - tổ chức quản l& yacute; t& ecirc;n miền quốc tế" } (JSON string contains Vietnamese accent)
But when process on server, I received error "Unterminated string. Expected delimiter: ". Line 1, position ...." (It looks like the error happened because of đ& oacute;). (In this page, I seperate & with character after it by a space, because it will automacally converted to a Vietnamese if there are no space)
There are no error if user input is English text (no Vietnamese accent).
Please guide me how to fix this error.
I know at this time this will probably not be useful for you, but maybe it can help another person.
You should convert your string to UTF8 to deal with accents (Vietnamese and many other languages) before serializing it to JSON. For that you can use this function:
private string ConvertToUtf8(string textOriginal)
{
if (!string.IsNullOrEmpty(textOriginal))
{
byte[] bytes = Encoding.Default.GetBytes(textOriginal);
return Encoding.UTF8.GetString(bytes);
}
return string.Empty;
}

How do I find out which suffix user has chosen when using a QFileDialog?

Well I'm using the following code to get the filename for a file that needs to be stored ..
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),"/home/user/MyDocs/",tr("JPG files (*.jpg);;BMP files (*.bmp);;PNG files (*.png)"));
I'm providing the user with a number of options regarding the file format in which the file is to be saved. However, the returned QString only gives me the prefix filename the user have chosen, not the suffix and thus I don't know which file format the user chose. How can I detect such a file format?
The code in the question works in Windows (Qt 4.6.2 and Win XP). fileName contains the selected extension. But you are obviously using something else Windows, so you could try this workaround:
QFileDialog dialog(this, tr("Save as ..."), "/home/user/MyDocs/");
dialog.setAcceptMode(QFileDialog::AcceptSave);
QStringList filters;
filters << "JPG files (*.jpg)" << "BMP files (*.bmp)" << "PNG files (*.png)";
dialog.setNameFilters(filters);
if (dialog.exec() == QDialog::Accepted)
{
QString selectedFilter = dialog.selectedNameFilter();
QString fileName = dialog.selectedFiles()[0];
}
That is a slighty modified code from here.
You need to use the 5th optional string
I usually do it like this:
#define JPEG_FILES "JPG files (*.jpg)"
#define BMP_FILES "BMP files (*.bmp)"
#define PNG_FILES "PNG files (*.png)"
QString selectedFilter;
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
"/home/user/MyDocs/",
JPEG_FILES ";;" BMP_FILES ";;" PNG_FILES, &selectedFilter);
if (fileName.isNull())
return;
if (selectedFilter == JPEG_FILES) {
...
} else if (selectedFilter == BMP_FILES) {
...
} else if (selectedFilter == PNG_FILES) {
...
} else {
// something strange happened
}
The compiler takes care to concatenate the literal strings in the argument.
I'm not sure how the returned string interacts with tr(). You'll have to test and find out. probably need to un-translate it.
It could have been nicer if the function would return the index of the selected filter but alas, it does not.
A nicer solution would be to put the filters in a list, create a string from it and then compare to the returned selected filter string to the ones in the list. This would also solve the tr() problem.
Have a look to this discussion. It uses QFileInfo on the string that was entered in a QFileDialog.

Resources