我有以下JSON文件:
{
"users":[
{"nom":"123",
"name":"John",
"family":"ala",
"cash":1000
}
,{"nom":"456",
"name":"Joe",
"family":"ala",
"cash":1000
}
,{"nom":"131",
"name":"David",
"family":"ala",
"cash":1000
}]
}
我想兑换John
的现金。
这就是我试图实现这一点的方法:
QFile f("file address ...");
f.open(QIODevice::ReadOnly|QIODevice::Text|QIODevice::WriteOnly);
QByteArray b=f.readAll();
QJsonDocument d=QJsonDocument::fromJson(b);
QJsonObject o=d.object();
for (int i=0;i<o["users"].toArray().size();i++) {
if(o["users"].toArray()[i].toObject()["name"].toString()=="John")
o["users"].toArray()[i].toObject()["cash"].toInt()=2000;//error unable to assign
}
但是,我得到了以下错误:
错误:无法分配
怎么解决这个问题?
您得到了错误,因为您正在尝试为函数的返回值赋值(在本例中为QJSONValue::ToInt
)。
将值分配给QJSONValue
,如JSON保存游戏示例所示:
void Character::write(QJsonObject &json) const
{
json["name"] = mName;
json["level"] = mLevel;
json["classType"] = mClassType;
}
下面是我为您编写的一个示例,目的是演示如何更改您的代码以实现建议的解决方案:
#include <QApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile file("data.json");
if (file.open(QFile::ReadOnly | QFile::Text)) {
QJsonObject json = QJsonDocument::fromJson(file.readAll()).object();
QJsonArray users = json["users"].toArray();
file.close();
for (auto user : users) {
QJsonObject userObj = user.toObject();
if (userObj["name"].toString() == "John")
userObj["cash"] = 2000;
user = userObj;
}
qDebug() << users;
}
return a.exec();
}
给出的示例产生以下结果:
QJsonArray([{"cash":2000,"family":"ala","name":"John","nom":"123"},{"cash":1000,"family":"ala","name":"Joe","nom":"456"},{"cash":1000,"family":"ala","name":"David","nom":"131"}])
请注意,john
的cash
设置为2000
。