Qt5有一个新的JSON解析器,我想使用它。问题在于,用外行的术语来说,它不太清楚这些函数的作用以及如何使用它编写代码。或者我可能读错了。
我想知道在Qt5中创建JSON文件的代码以及"封装"的内容。的意思。
示例:从文件
读取json/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
示例:从string 读取json
如下所示将json赋值给string,并使用readJson()
函数:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
JSON在QT下实际上是相当愉快的-我很惊讶。这是一个如何创建具有某种结构的JSON输出的示例。
请原谅我没有解释所有字段的含义-这是一个业余无线电处理输出脚本。
这是QT c++代码
void CabrilloReader::JsonOutputMapper()
{
QFile file(QDir::homePath() + "/1.json");
if(!file.open(QIODevice::ReadWrite)) {
qDebug() << "File open error";
} else {
qDebug() <<"JSONTest2 File open!";
}
// Clear the original content in the file
file.resize(0);
// Add a value using QJsonArray and write to the file
QJsonArray jsonArray;
for(int i = 0; i < 10; i++) {
QJsonObject jsonObject;
CabrilloRecord *rec= QSOs.at(i);
jsonObject.insert("Date", rec->getWhen().toString());
jsonObject.insert("Band", rec->getBand().toStr());
QJsonObject jsonSenderLatObject;
jsonSenderLatObject.insert("Lat",rec->getSender()->fLat);
jsonSenderLatObject.insert("Lon",rec->getSender()->fLon);
jsonSenderLatObject.insert("Sender",rec->getSender_call());
QJsonObject jsonReceiverLatObject;
jsonReceiverLatObject.insert("Lat",rec->getReceiver()->fLat);
jsonReceiverLatObject.insert("Lon",rec->getReceiver()->fLon);
jsonReceiverLatObject.insert("Receiver",rec->getReceiver_call());
jsonObject.insert("Receiver",jsonReceiverLatObject);
jsonObject.insert("Sender",jsonSenderLatObject);
jsonArray.append(jsonObject);
QThread::sleep(2);
}
QJsonObject jsonObject;
jsonObject.insert("number", jsonArray.size());
jsonArray.append(jsonObject);
QJsonDocument jsonDoc;
jsonDoc.setArray(jsonArray);
file.write(jsonDoc.toJson());
file.close();
qDebug() << "Write to file";
}
它需要一个内部QT结构(一个指向CabrilloRecord对象的指针列表…您可以忽略它)并提取一些字段。这些字段然后以嵌套的JSON格式输出,如下所示:
[
{
"Band": "20",
"Date": "Sat Jul 10 12:00:00 2021",
"Receiver": {
"Lat": 36.400001525878906,
"Lon": 138.3800048828125,
"Receiver": "8N3HQ "
},
"Sender": {
"Lat": 13,
"Lon": 122,
"Sender": "DX0HQ "
}
},
{
"Band": "20",
"Date": "Sat Jul 10 12:01:00 2021",
"Receiver": {
"Lat": 36.400001525878906,
"Lon": 138.3800048828125,
"Receiver": "JA1CJP "
},
"Sender": {
"Lat": 13,
"Lon": 122,
"Sender": "DX0HQ "
}
}]
我希望这能加快其他人在这个话题上的进展。
遗憾的是,许多JSON c++库都有一些不易使用的api,而JSON旨在易于使用。
所以我尝试了jsoncpp从gSOAP工具上的JSON文档显示在上面的答案之一,这是用jsoncpp生成的代码,在c++中构建一个JSON对象,然后以JSON格式写入std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
,这是jsoncpp生成的代码,用于从std::cin解析JSON并提取其值(根据需要替换USE_VAL
):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
此代码使用gSOAP 2.8.28的JSON c++ API。我不希望人们改变库,但我认为这种比较有助于正确看待JSON c++库。
如果能举例说明就好了。Qt论坛上有几个例子,但是你是对的,官方文档应该扩展。
QJsonDocument
本身确实不会产生任何东西,您将不得不向其添加数据。这是通过QJsonObject
, QJsonArray
和QJsonValue
类完成的。顶级项需要是数组或对象(因为1
不是有效的json文档,而{foo: 1}
是)