C++ 如何从 QString 初始化 QJsonObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26804660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize QJsonObject from QString
提问by Ioan Paul Pirau
I am quite new to Qt and I have a very simple operation that I want to do: I have to obtain the following JSonObject:
我对 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"]
}
]
}
The JSon was checked with this Syntax and Validity checker: http://jsonformatter.curiousconcept.com/and was found valid.
使用此语法和有效性检查器检查 JSon:http://jsonformatter.curiousconcept.com/并发现有效。
I used QJsonValue initialization of String for that and converted it to QJSonObject:
我为此使用了 String 的 QJsonValue 初始化并将其转换为 QJSonObject:
QJsonObject ObjectFromString(const QString& in)
{
QJsonValue val(in);
return val.toObject();
}
I am loading the JSon pasted up from a file:
我正在加载从文件粘贴的 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;
There's most certainly a good way to do this because this is not working, and I didn't find any helpful examples
肯定有一个很好的方法来做到这一点,因为这不起作用,而且我没有找到任何有用的例子
回答by TheDarkKnight
QString data; // assume this holds the json string
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
If you want the QJsonObject...
如果你想要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;
}
回答by Joe
You have to follow this step
你必须按照这一步
- convert Qstring to QByteArray first
- convert QByteArray to QJsonDocument
- convert QJsonDocument to QJsonObject
- 首先将 Qstring 转换为 QByteArray
- 将 QByteArray 转换为 QJsonDocument
- 将 QJsonDocument 转换为 QJsonObject
QString str = "{\"name\" : \"John\" }";
QByteArray br = str.toUtf8();
QJsonDocument doc = QJsonDocument::fromJson(br);
QJsonObject obj = doc.object();
QString name = obj["name"].toString();
qDebug() << name;