一、构建和解析单个JSON对象
1.1 JSON对象的构建
使用key-value形式生成JSON对象
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
int main() {
// 创建 JSON 对象
QJsonObject jsonObj;
jsonObj["name"] = "张三";
jsonObj["age"] = 28;
jsonObj["isStudent"] = false;
// 转为 JSON 字符串
QJsonDocument doc(jsonObj);
QString strJson(doc.toJson(QJsonDocument::Compact)); // 或 Indented
// 输出 JSON 字符串
qDebug() << strJson;
return 0;
}
输出结果:
{
"name":"张三","age":28,"isStudent":false}
使用insert函数生成JSON对象
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
int main()
{
// 创建 JSON 对象
QJsonObject jsonObj;
jsonObj.insert("name", "李四");
jsonObj.insert("age", 30);
jsonObj.insert("isStudent", false);
// 转为 JSON 字符串
QJsonDocument doc(jsonObj);
QString strJson(doc.toJson(QJsonDocument::Indented)); // 或 Indented
// 输出 JSON 字符串
qDebug() << strJson;
return 0;
}
输出结果:
{
"name":"李四","age":30,"isStudent":false}
1.2 JSON对象的解析
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
int main()
{
QString jsonString = R"({"name":"张三","age":28,"isStudent":false})";
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8(), &parseError);
if (parseError.error != QJsonParseError::NoError) {
qDebug() << "解析错误:" << parseError.errorString();
return -1;
}
if (!doc.isObject()) {
qDebug() << "JSON 不是对象类型";
return -1;
}
QJsonObject obj = doc.object();
// 判断并提取 name
if (obj.contains("name") && obj["name"].isString()) {
QString name = obj["name"].toString();
qDebug() << "姓名:" << name;
} else {
qDebug() << "字段 'name' 缺失或类型错误";
}
// 判断并提取 age
if (obj.contains("age") && obj["age"].isDouble()) {
int age = obj["age"].toInt();
qDebug() << "年龄:" << age;
} else {
qDebug() << "字段 'age' 缺失或类型错误";
}
// 判断并提取 isStudent
if (obj.contains("isStudent") && obj["isStudent"].isBool()) {
bool isStudent = obj["isStudent"].toBool();
qDebug() << "是否学生:" <<

最低0.47元/天 解锁文章
1583

被折叠的 条评论
为什么被折叠?



