gpt4 book ai didi

c++ - 如何从 QString 初始化 QJsonObject

转载 作者:IT老高 更新时间:2023-10-28 21:39:06 26 4
gpt4 key购买 nike

我对 Qt 很陌生,我想做一个非常简单的操作:我必须获得以下JSonObject:

{
"Record1" : "830957 ",
"Properties" :
[{
"Corporate ID" : "3859043 ",
"Name" : "John Doe ",
"Function" : "Power Speaker ",
"Bonus Points" : ["10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56", "10 ", "45", "56 ", "34", "56 ", "10", "45 ", "56", "34 ", "56", "45"]
}
]
}

使用此语法和有效性检查器检查了 JSON:http://jsonformatter.curiousconcept.com/并且被发现有效。

我为此使用了 String 的 QJsonValue 初始化并将其转换为 QJSonObject:

QJsonObject ObjectFromString(const QString& in)
{
QJsonValue val(in);
return val.toObject();
}

我正在加载从文件中粘贴的 JSon:

QString path = "C:/Temp";
QFile *file = new QFile(path + "/" + "Input.txt");
file->open(QIODevice::ReadOnly | QFile::Text);
QTextStream in(file);
QString text = in.readAll();
file->close();

qDebug() << text;
QJsonObject obj = ObjectFromString(text);
qDebug() <<obj;

肯定有一个好方法可以做到这一点,因为这不起作用,而且我没有找到任何有用的例子

最佳答案

使用 QJsonDocument::fromJson

QString data; // assume this holds the json string

QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());

如果您想要 QJsonObject ...

QJsonObject ObjectFromString(const QString& in)
{
QJsonObject obj;

QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8());

// check validity of the document
if(!doc.isNull())
{
if(doc.isObject())
{
obj = doc.object();
}
else
{
qDebug() << "Document is not an object" << endl;
}
}
else
{
qDebug() << "Invalid JSON...\n" << in << endl;
}

return obj;
}

关于c++ - 如何从 QString 初始化 QJsonObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26804660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com