C++ 使用Qt解析带有国家代码的Json文件
我需要解析一个包含国家名称和ISD拨号代码的长json文件。我需要把它们最好放在QVector或数组中,这样我就可以在下拉菜单中填充它们,比如QComboBox 我尝试使用QJsonObject类,但无法按预期进行解析。长度返回零 这是我的示例文件C++ 使用Qt解析带有国家代码的Json文件,c++,json,qt,C++,Json,Qt,我需要解析一个包含国家名称和ISD拨号代码的长json文件。我需要把它们最好放在QVector或数组中,这样我就可以在下拉菜单中填充它们,比如QComboBox 我尝试使用QJsonObject类,但无法按预期进行解析。长度返回零 这是我的示例文件 [{ "name": "Afghanistan", "dial_code": "+93", "code": "AF" }, { "name": "Aland Islands", "dial_code":
[{
"name": "Afghanistan",
"dial_code": "+93",
"code": "AF"
},
{
"name": "Aland Islands",
"dial_code": "+358",
"code": "AX"
},
{
"name": "Albania",
"dial_code": "+355",
"code": "AL"
},
{
"name": "Algeria",
"dial_code": "+213",
"code": "DZ"
}]
我尝试了以下代码:
QJsonDocument doc = QJsonDocument::fromJson(jsonFile->readAll());
jsonFile->close();
if(!doc.isNull())
{
qDebug() << "Good Json document";
}
QJsonObject jObject = doc.object();
qDebug() << "length : " << jObject.length();
QJsonObject::iterator i;
for (i = jObject.begin(); i != jObject.end(); ++i)
{
if (i.value().isNull())
qDebug() << i.key();
else
qDebug() << i.key() << i.value();
}
您将文档的根对象解释为JSON对象,而不是实际的数组。您应该使用以下代码:
QJsonArray rootArray = doc.array();
而不是
QJsonObject jObject = doc.object();
然后,可以迭代该数组中包含的各种对象
在调用QJsonDocument::array或QJsonDocument::object之前,请查看并测试您正在处理的是数组还是对象我花了太多时间来回答,所以我对@epsilon的答案投了赞成票。这个答案就成了一个补充
问题是您正在将QJsonArray作为QJsonObject处理
事实上,您的数据是QJSONObject的QJsonArray。
更清楚地说,您有一个数组,它是一个对象列表
我编写了一个简短的示例来精确解析您的数据格式:
int main()
{
QFile json_file("path/to/your/file.json");
// Read the file
if(!json_file.open(QIODevice::ReadOnly))
return -1;
QByteArray json_raw = json_file.readAll();
json_file.close();
// Parse the json
QJsonParseError json_error;
QJsonDocument doc = QJsonDocument::fromJson(json_raw, &json_error);
if(json_error.error != QJsonParseError::NoError)
return -1;
// Parse your specific data
QVector <QJsonObject> contents;
if(!parseJsonCountries(doc, contents))
return -1;
// Display the contents
for(const QJsonObject & item : contents)
{
qDebug() << item.value("name").toString() << " : " << item.value("dial_code").toString() << " : " << item.value("code").toString();
}
return 0;
}
这里有解析函数:
bool parseJsonCountries(const QJsonDocument & doc, QVector<QJsonObject> & contents)
{
if(!doc.isArray())
return false;
QJsonArray data = doc.array();
QJsonObject obj;
for(QJsonValueRef item : data)
{
if(!item.isObject())
return false;
obj = item.toObject();
if(obj.size() != 3)
return false;
if( ! (obj.contains("name") && obj.contains("dial_code") && obj.contains("code")) )
return false;
contents << obj;
}
return true;
}
我已经尽力为您提供了一个函数,可以按照您最初的需要将数据存储在QVector中
我希望它能有所帮助。展示你的尝试,即使没有work@eyllanesc我放了试用码你用过文件的完整路径吗?您确定QFile正确打开了文件吗?@eyllanesc是的,当我打开qDebugIn时,我可以看到文件的内容。我的案例长度返回1。