Sajmplus Sajmplus - 15 days ago 5x
JSON Question

QJsonObject and international characters

I have problem with

character encoding.
returns string with international characters as hex values:

s: "żółć"
obj: QJsonObject({"s":"żółć"})
doc: QJsonDocument({"s":"żółć"})
JSON: "{\n \"s\": \"\xC5\xBC\xC3\xB3\xC5\x82\xC4\x87\"\n}\n"


#include <QCoreApplication>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>

int main(int argc, char *argv[])
QCoreApplication a(argc, argv);

QString s = "żółć";
qDebug() << "s: " << s;

QJsonObject obj;
obj["s"] = s;
qDebug() << "obj: " << obj;

QJsonDocument doc(obj);
qDebug() << "doc: " << doc;

qDebug() << "JSON: " << doc.toJson();

return a.exec();

How can I get JSON string with international characters?


QJsonObject::toJson() returns string with national characters as hex values

Assuming you meant QJsonDocument::toJson() this is not true, QJsonDocument::toJson() returns a QByteArray encoded in UTF-8, this way it is capable of encoding all possible characters, or code points, defined by Unicode. After that, you can send/save the result QByteArray to be read and parsed later, and you should be able to get your original string out of it.

So, the HEX characters you are seeing in the debug output are not really there, they are just QDebug's way of printing QByteArrays:

Normally, QDebug prints the array inside quotes and transforms control or non-US-ASCII characters to their C escape sequences (\xAB). This way, the output is always 7-bit clean and the string can be copied from the output and pasted back into C++ sources, if necessary.

You can use qDebug().noqoute() to see how your JSON byte array looks like without escaping those characters:

qDebug().noquote() << "JSON: " << doc.toJson();

Or, you can print it as a QString instead:

qDebug() << "JSON: " << QString::fromUtf8(doc.toJson());


It is very bad practice to put non-ascii chars in string literals. You should read them from a resource or an escaped string literal while specifying their encoding (maybe using QString::fromUtf8(), QString::fromUtf16(), ...).