Re: reading JSON file in Qt5
Does /tmp/settings.json exists? Is it well formed? Also try QJsonDocument::fromJson and see what error (QJsonParseError) you get.
EDIT: Forget the first questions....
EDIT 2:
Code:
" \"Herausgeber\": \"Xema\","
" \"Nummer\": \"1234-5678-9012-3456\","
" \"Deckung\": 2e+6,"
" \"Währung\": \"EURO\","
" \"Inhaber\": {"
" \"Name\": \"Mustermann\","
" \"Vorname\": \"Max\","
" \"männlich\": true,"
" \"Hobbys\": [ \"Reiten\", \"Golfen\", \"Lesen\" ],"
" \"Alter\": 42,"
" \"Kinder\": [],"
" \"Partner\": null"
" }"
"}";
QJsonDocument d = QJsonDocument::fromJson(str.toUtf8());
qWarning() << d.isNull();
See if that works for you and then replace str.toUtf8() through your readAll().
[Solved] Re: reading JSON file in Qt5
Thank you for your fast reply and even more thank you for your example code!!
It works now! I somehow overlooked that I can use toUtf8() on a QString.
You example put me in the right track and now I can adjust basic window properties with my json file :D
Now just need to work on auto copy this file into the apps resources at runtime.
Here is my working code::
Code:
file.setFileName("/tmp/settings.json");
settings = file.readAll();
file.close();
QJsonDocument sd = QJsonDocument::fromJson(settings.toUtf8());
qWarning() << sd.isNull(); // <- print false :)
QJsonObject sett2 = sd.object();
qWarning
() << sett2.
value(QString("title"));
// <- print my title
Thanks again, totally made my morning :)
Laszlo
Re: [Solved] Re: reading JSON file in Qt5
You are aware that this requires two codec conversions, right?
Code:
settings = file.readAll()
converts from UTF-8 to UTF-16 and
converts from UTF-16 to UTF-8.
Since start and end encoding are the same (UTF-8) those two conversions are unneeded.
Why don't you just call fromJson() with the QByteArray returned by file.readAll()?
Also: the problem with your original code has nothing to do with the content at all, you are calling a static method and are then wondering why it didn't change an instance.
Static methods can't do that.
Hint: in Qt methods that are called fromABCD usually return something.
Cheers,
_
Re: [Solved] Re: reading JSON file in Qt5
QString filename = QFileDialog::getOpenFileName();
QString val;
QFile file;
file.setFileName(filename);
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject Documento = d.object();
//{}= objet [] Array