我是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"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
使用此语法和有效性检查器检查了JSon:http://jsonformatter.curiousconcept.com/ 并且被发现有效.
我为此使用了字符串的QJsonValue初始化并将其转换为QJSonObject:
QJsonObject ObjectFromString(const QString& in)
{
QJsonValue val(in);
return val.toObject();
}
Run Code Online (Sandbox Code Playgroud)
我正在加载从文件粘贴的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;
Run Code Online (Sandbox Code Playgroud)
这肯定是一种很好的方法,因为这不起作用,我没有找到任何有用的例子
The*_*ght 30
QString data; // assume this holds the json string
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
Run Code Online (Sandbox Code Playgroud)
如果你想要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;
}
Run Code Online (Sandbox Code Playgroud)
你必须遵循这个步骤
QString str = "{\"name\" : \"John\" }";
QByteArray br = str.toUtf8();
QJsonDocument doc = QJsonDocument::fromJson(br);
QJsonObject obj = doc.object();
QString name = obj["name"].toString();
qDebug() << name;
Run Code Online (Sandbox Code Playgroud)