Qt之JSON字符串的序列化和反序列化

一、简介

JSON 用于存储结构化的数据,存储的格式为:bool、double、string、array、object、null等6种格式。bool 值用“true/false”表示, double 支持双精度;string 代表字符串;array 数组是列表,用方括号“[]”表示;object 对象是“键值对”组合,并且都是字符串,不能包含重复的 key,用大括号“{}”表示。JSON中的每条都用逗号隔开。如下是一个示例:

{
   "Time" : 10,
  "Win10" : true,
  "ComputerType" : "Lenovo",

   "Hardware" : {
       "CPU" : "3.0GHZ",
        "Processor" : "i7-9700F",
       "RAM" : "16GB"
      "Windows" : {
       "Version" : "Windows10",
       "VersionNumber" : "21H2",
       "InstallDate" : "2022/04/28"
   }

   "Software" : [
       "Office",
       "Photoshop"
  ]

   "UserName" : {
    
  }
 
}      

 以上是常见6种存储格式,且Qt中的JSON类可分为QJsonValue(封装JSON值)、QJsonArray(封装JSON数组)、QJsonObject(封装JSON对象)、QJsonDocument(封住JSON文档)、QJsonParseError(解析JSON时的错误)等类。

二、构建JSON对象

    //构建复杂JSON字符串
    QJsonObject winObject;
    winObject.insert("Version", "Windows10");
    winObject.insert("VersionNumber", "21H2");
    winObject.insert("InstallDate", "2022/04/28");

   QJsonObject hardObject;
   hardObject.insert("CPU", "3.0GHZ");
   hardObject.insert("Processor", "i7-9700F");
   hardObject.insert("RAM", "16GB");
   hardObject.insert("Windows", QJsonValue(winObject));

   //构建JSON数组
   QJsonArray jsonArray;
   jsonArray.append("Office");
   jsonArray.append("Photoshop");

   //构建JSON对象
   QJsonObject object;
   object.insert("Time", 10);
   object.insert("Win10", true);
   object.insert("ComputerType", "Lenovo");
   object.insert("UserName", QJsonObject()); //构建空json
   object.insert("Hardware", QJsonValue(hardObject));
   object.insert("Software", QJsonValue(jsonArray));

   QJsonDocument document;
   document.setObject(object);
   m_arrayJson = document.toJson(QJsonDocument::Compact);

三、解析JSON对象

  QString array;

    QJsonParseError jsonError;
    QJsonDocument document = QJsonDocument::fromJson(m_arrayJson, &jsonError);
    if (!document.isNull() && (QJsonParseError::NoError == jsonError.error)) {
        //解析JSON对象
        if (document.isObject()) {
            QJsonObject object = document.object();
            if (object.contains("Time")) {
                QJsonValue value = object.take("Time");
                if (value.isDouble()) {
                    int nTime = value.toVariant().toInt();
                    array.append(QString("Time : %1; ").arg(nTime));
                }
            }
            if (object.contains("Win10")) {
                QJsonValue value = object.take("Win10");
                if (value.isBool()) {
                    bool bWin10= value.toVariant().toBool();
                    array.append(QString("Win10 : %1; ").arg(bWin10));
                }
            }
            if (object.contains("ComputerType")) {
                QJsonValue value = object.take("ComputerType");
                if (value.isString()) {
                    QString strType = value.toVariant().toString();
                    array.append(QString("ComputerType : %1; ").arg(strType));
                }
            }
            //解析JSON数组
            if (object.contains("Software")) {
                QJsonValue value = object.take("Software");
                if (value.isArray()) {

                    QJsonArray arrayJson = value.toArray();
                    for (int var = 0; var < arrayJson.size(); ++var) {
                        value = arrayJson.at(var);
                        if (value.isString()) {
                            QString strOffice = value.toString();
                            if (var > 0) {
                               array.append(QString("%1; ").arg(strOffice));
                            } else {
                               array.append(QString("Software: %1, ").arg(strOffice));

                            }
                        }
                    }

                }
            }
            //解析复杂JSON字符串
            if (object.contains("Hardware")) {
                QJsonValue hardValue = object.take("Hardware");
                if (hardValue.isObject()) {
                    QJsonObject harObject = hardValue.toObject();
                    if (harObject.contains("Windows")) {
                        QJsonValue winValue = harObject.take("Windows");
                        if (winValue.isObject()) {
                            QJsonObject winObject = winValue.toObject();
                            if (winObject.contains("Version")) {
                                QJsonValue verJson = winObject.take("Version");
                                if (verJson.isString()) {
                                    QString strVer = verJson.toVariant().toString();
                                    array.append(QString("Version : %1, ").arg(strVer));
                                }
                            }
                        }
                    }
                    if (harObject.contains("CPU")) {
                        QJsonValue value = harObject.take("CPU");
                        if (value.isString()) {
                            QString strCPU = value.toVariant().toString();
                            array.append(QString("CPU : %1").arg(strCPU));
                        }
                    }
                }

            }
        }
    }
    m_editParse->setText(array);

结果如下图所示

四、JSON数组的解析

[
    {
        "cid": "CN01",
        "city": "北京",
        "nation": "中国",
    },
    
    {
        "cid": "US02",
        "city": "华盛顿",
        "nation:" "美国"
    },
]

json数组示例一:

QJsonObject cn_json;
cn_json.insert("cid", "CN01");
cn_json.insert("city", "beijing");
cn_json.insert("nation", "china");

QJsonObject us_json;
us_json.insert("cid", "US02");
us_json.insert("city", "washington");
us_json.insert("nation", "us");

QJsonArray array;
array.append(QJsonValue(cn_json));
array.append(QJsonValue(us_json));

QByteArray data = QJsonDocument(array).toJson(QJsonDocument::Compact);

json数组解析

QJsonParseError jsonError;
QJsonDocument document = QJsonDocument::fromJson(data, &jsonError);
if (jsonError.error == QJsonParseError::NoError) {
    QVariantList list = document.toVariant().toList();
    foreach (QVariant variant, list) {
      qDebug() << "cid:" <<  variant.toMap()["cid"].toString();
      qDebug() << "city:" << variant.toMap()["city"].toString();
      qDebug() << "nation:" << variant.toMap()["nation"].toString();
   }
}

json数组示例二:

QJsonObject json_1;
json_1.insert("id", "20230402221529");

QJsonObject json_2;
json_2.insert("id", "20230402203158");

QJsonObject json_3;
json_3.insert("id", "20230402175752");

QJsonArray array;
array.append(QJsonValue(json_1));
array.append(QJsonValue(json_2));
array.append(QJsonValue(json_3));

QJsonObject json;
json.insert("data", QJsonValue(array));

QByteArray data = QJsonDocument(json).toJson(QJsonDocument::Compact);
qDebug() << "data:" << data;

json数组解析

QJsonParseError jsonError;
QJsonDocument json_doc = QJsonDocument::fromJson(data, &jsonError);
    if (jsonError.error == QJsonParseError::NoError) {
        QJsonObject root_obj = json_doc.object();
        if (root_obj.contains("data")) {
            QJsonValue json_value = root_obj.value("data");
            if (json_value.isArray()) {
                QJsonArray array = json_value.toArray();
                for (int i = 0; i < array.size(); ++i) {
                    QJsonValue id_value = array.at(i);
                    if (id_value.isObject()) {
                        QJsonObject id_object = id_value.toObject();
                        qDebug() << "id:" << id_object.take("id").toVariant().toString();
                         //QString id = id_object["id"].toString();
                         //qDebug() << "id:" << id;
                    }
                }
            }

        }
    }
posted @ 2022-07-10 22:39  TechNomad  阅读(3382)  评论(0编辑  收藏  举报