Qt实现json数据的生成、解析、修改和删除

文章介绍

  • 本文章主要介绍如何使用QT提供的json相关类来处理json数据,包括json数据的生成、解析、修改和json数据的删除。

json数据的增删改查

  • 处理json数据时需要包含以下三个头文件
    •   #include 
        #include 
        #include 
      

json数据生成

  • json数据
    •   {  
            "id":1001,
            "name":"jack",
            "sex":true
        }
      
  • 代码
    •   // 创建json数据对象
        QJsonObject json;
        json.insert("name", "jack");
        json.insert("id", 1001);
        json.insert("sex", true);
      
      
        QJsonDocument document;   // 创建json文档
        document.setObject(json); // 给json文档设置json数据对象
        // 将json数据对象转为字符串
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

嵌套json数据生成

  • json数据
    •   {
            "id": 1002,
            "name": "Tom",
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 代码
    •   // 创建子节点scoreData的json数据对象
        QJsonObject scoreObject;
        scoreObject.insert("Math", 90);
        scoreObject.insert("Chinese", 96);
        scoreObject.insert("English", 82);
      
        // 创建json数据对象
        QJsonObject json;
        json.insert("name", "Tom");
        json.insert("id", 1002);
        json.insert("sex", true);
        json.insert("scoreData", QJsonValue(scoreObject));
      
        QJsonDocument document;
        document.setObject(json);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

包含数组的json数据生成

  • json数据
    •   {
            "id":1002,
            "name": "Tom",
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex": true,
            "techData":["C++", "JAVA", "PYTHON"]
        }
      
  • 代码
    •   // 创建json数组对象
        QJsonArray techArray;
        techArray.append("C++");
        techArray.append("JAVA");
        techArray.append("PYTHON");
      
        // 创建子节点scoreData的json数据对象
        QJsonObject scoreObject;
        scoreObject.insert("Math", 90);
        scoreObject.insert("Chinese", 96);
        scoreObject.insert("English", 82);
      
        // 创建json对象
        QJsonObject json;
        json.insert("name", "Tom");
        json.insert("id", 1002);
        json.insert("sex", true);
        json.insert("scoreData", QJsonValue(scoreObject));
        json.insert("techData", QJsonValue(techArray));
      
      
        QJsonDocument document;
        document.setObject(json);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

包含数组对象的json数据生成

  • json数据
    •   {
            "id":1002,
            "name": "Tom",
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"xiaoxue"},
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 代码
    •   // 创建json数组
        QJsonArray SchoolArray;
      
        QJsonObject primarySchoolObj;
        primarySchoolObj.insert("schoolName", "xiaoxue");
        primarySchoolObj.insert("schoolCity", "Xian");
      
        QJsonObject middleSchoolObj;
        middleSchoolObj.insert("schoolName", "zhongxue");
        middleSchoolObj.insert("schoolCity", "Xian");
      
        QJsonObject universityObj;
        universityObj.insert("schoolName", "daxue");
        universityObj.insert("schoolCity", "Beijing");
      
        // json数组中插入json数据对象
        SchoolArray.append(primarySchoolObj);
        SchoolArray.append(middleSchoolObj);
        SchoolArray.append(universityObj);
      
        // 创建子节点scoreData的json数据对象
        QJsonObject scoreObject;
        scoreObject.insert("Math", 90);
        scoreObject.insert("Chinese", 96);
        scoreObject.insert("English", 82);
      
        // 创建json数据
        QJsonObject json;
        json.insert("name", "Tom");
        json.insert("id", 1002);
        json.insert("sex", true);
        json.insert("scoreData", QJsonValue(scoreObject));
        json.insert("schoolData", QJsonValue(SchoolArray));
      
        QJsonDocument document;
        document.setObject(json);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

json数据解析

  • json数据
    •   {
            "sex":true,
            "id":1001,
            "name":"jack"
        }
      
  • 解析结果
    •   strName "jack"
        iId 1001
        bSex true
      
  • 代码
    •   QByteArray jsonData = "{\"sex\":true,\"id\":1001,\"name\":\"jack\"}";
      
        // 将字符串转为json文档
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        // 获取根对象
        QJsonObject rootObj = rootDoc.object();
      
        // 解析json数据
        QJsonValue nameValue = rootObj.value("name");
        QString strName = nameValue.toString();
        qDebug() << "strName" << strName;
      
        QJsonValue idValue = rootObj.value("id");
        int iId = idValue.toInt();
        qDebug() << "iId" << iId;
      
        QJsonValue sexValue = rootObj.value("sex");
        bool bSex = sexValue.toBool();
        qDebug() << "bSex" << bSex;
      

嵌套json数据解析

  • json数据
    •   {
            "id":1002,
            "name":"Tom",
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 解析结果
    •   strName "Tom"
        iId 1002
        bSex true
        iChinese 96
        iEnglish 82
        iMath 90
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true}";
      
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        // 获取根对象
        QJsonObject rootObj = rootDoc.object();
      
        // 解析json数据
        QJsonValue nameValue = rootObj.value("name");
        QString strName = nameValue.toString();
        qDebug() << "strName" << strName;
      
        QJsonValue idValue = rootObj.value("id");
        int iId = idValue.toInt();
        qDebug() << "iId" << iId;
      
        QJsonValue sexValue = rootObj.value("sex");
        bool bSex = sexValue.toBool();
        qDebug() << "bSex" << bSex;
      
        // 解析scoreData节点的json数据
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
      
        QJsonValue chineseValue = scoreDataObj.value("Chinese");
        int iChinese = chineseValue.toInt();
        qDebug() << "iChinese" << iChinese;
      
        QJsonValue englishValue = scoreDataObj.value("English");
        int iEnglish = englishValue.toInt();
        qDebug() << "iEnglish" << iEnglish;
      
        QJsonValue mathValue = scoreDataObj.value("Math");
        int iMath = mathValue.toInt();
        qDebug() << "iMath" << iMath;
      

包含数组的json数据解析

  • json数据
    •   {
            "id":1002,
            "name":"Tom",
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true,
            "techData":["C++", "JAVA", "PYTHON"]
        }
      
  • 解析结果
    •   strName "Tom"
        iId 1002
        bSex true
        iChinese 96
        iEnglish 82
        iMath 90
        str "C++"
        str "JAVA"
        str "PYTHON"
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true,\"techData\":[\"C++\",\"JAVA\",\"PYTHON\"]}";
      
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        // 获取根对象
        QJsonObject rootObj = rootDoc.object();
      
        // 解析json数据
        QJsonValue nameValue = rootObj.value("name");
        QString strName = nameValue.toString();
        qDebug() << "strName" << strName;
      
        QJsonValue idValue = rootObj.value("id");
        int iId = idValue.toInt();
        qDebug() << "iId" << iId;
      
        QJsonValue sexValue = rootObj.value("sex");
        bool bSex = sexValue.toBool();
        qDebug() << "bSex" << bSex;
      
        // 解析scoreData节点的json数据
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
      
        QJsonValue chineseValue = scoreDataObj.value("Chinese");
        int iChinese = chineseValue.toInt();
        qDebug() << "iChinese" << iChinese;
      
        QJsonValue englishValue = scoreDataObj.value("English");
        int iEnglish = englishValue.toInt();
        qDebug() << "iEnglish" << iEnglish;
      
        QJsonValue mathValue = scoreDataObj.value("Math");
        int iMath = mathValue.toInt();
        qDebug() << "iMath" << iMath;
      
        // 解析techData数组中的json数据
        QJsonValue techDataValue = rootObj.value("techData");
        QJsonArray techDataArray = techDataValue.toArray();
        for(int i = 0; i < techDataArray.size(); i++){
            QJsonValue value = techDataArray.at(i);
            QString str = value.toString();
            qDebug() << "str" << str;
        }
      

包含数组对象的json数据解析

  • json数据
    •   {
            "id":1002,
            "name":"Tom",
            "schoolData":[
                {
                    "schoolCity":"Xian",
                    "schoolName":"xiaoxue"
                },
                {
                    "schoolCity":"Xian",
                    "schoolName":"zhongxue"
                },
                {
                    "schoolCity":"Beijing",
                    "schoolName":"daxue"
                }
            ],
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 解析结果
    •   strName "Tom"
        iId 1002
        bSex true
        iChinese 96
        iEnglish 82
        iMath 90
        strSchoolname "xiaoxue"
        strSchoolcity "Xian"
        strSchoolname "zhongxue"
        strSchoolcity "Xian"
        strSchoolname "daxue"
        strSchoolcity "Beijing"
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"schoolData\":[{\"schoolCity\":\"Xian\",\"schoolName\":\"xiaoxue\"},{\"schoolCity\":\"Xian\",\"schoolName\":\"zhongxue\"},{\"schoolCity\":\"Beijing\",\"schoolName\":\"daxue\"}],\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true}";
      
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        // 获取根对象
        QJsonObject rootObj = rootDoc.object();
      
        // 解析json数据
        QJsonValue nameValue = rootObj.value("name");
        QString strName = nameValue.toString();
        qDebug() << "strName" << strName;
      
        QJsonValue idValue = rootObj.value("id");
        int iId = idValue.toInt();
        qDebug() << "iId" << iId;
      
        QJsonValue sexValue = rootObj.value("sex");
        bool bSex = sexValue.toBool();
        qDebug() << "bSex" << bSex;
      
        // 解析scoreData节点的json数据
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
      
        QJsonValue chineseValue = scoreDataObj.value("Chinese");
        int iChinese = chineseValue.toInt();
        qDebug() << "iChinese" << iChinese;
      
        QJsonValue englishValue = scoreDataObj.value("English");
        int iEnglish = englishValue.toInt();
        qDebug() << "iEnglish" << iEnglish;
      
        QJsonValue mathValue = scoreDataObj.value("Math");
        int iMath = mathValue.toInt();
        qDebug() << "iMath" << iMath;
      
        // 解析schoolData数组对象的json数据
        QJsonValue schoolDataValue = rootObj.value("schoolData");
        QJsonArray schoolDataValueArray = schoolDataValue.toArray();
      
        for(int i = 0; i < schoolDataValueArray.size(); i++){
            QJsonValue value = schoolDataValueArray.at(i);
            QJsonObject obj = value.toObject();
      
            QJsonValue schoolnameValue = obj.value("schoolName");
            QString strSchoolname = schoolnameValue.toString();
            qDebug() << "strSchoolname" << strSchoolname;
      
            QJsonValue schoolcityValue = obj.value("schoolCity");
            QString strSchoolcity = schoolcityValue.toString();
            qDebug() << "strSchoolcity" << strSchoolcity;
        }
      

json数据修改

  • 原始json数据
    •   {
            "id":1002,
            "name":"Tom",
            "techData":["C++","JAVA","PYTHON"], 
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"xiaoxue"},
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 修改后的json数据
    •   {
            "id":1002,
            "name":"Jack", // Tom修改为Jack
            "techData":["C++","JAVA","GO"], // PYTHON修改为GO 
            "schoolData":[
                {"schoolCity":"Baoji","schoolName":"xiaoxue"}, // Xian改为Baoji
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "Chinese":100, // 96修改为100
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"techData\":[\"C++\",\"JAVA\",\"PYTHON\"], \"schoolData\":[{\"schoolCity\":\"Xian\",\"schoolName\":\"xiaoxue\"},{\"schoolCity\":\"Xian\",\"schoolName\":\"zhongxue\"},{\"schoolCity\":\"Beijing\",\"schoolName\":\"daxue\"}],\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true}";
      
        // 将json数据转为json文档
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        // 获取根对象
        QJsonObject rootObj = rootDoc.object();
      
        // 修改数据
        rootObj["name"] = "Jack";
      
        // 修改数据对象
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
        scoreDataObj["Chinese"] = 100;
        rootObj["scoreData"] = scoreDataObj;
      
        // 修改数组
        QJsonValue techDataValue = rootObj.value("techData");
        QJsonArray techDataArray = techDataValue.toArray();
        for(int i = 0; i < techDataArray.size(); i++){
            if(techDataArray.at(i).toString().compare("PYTHON") == 0){
                techDataArray.replace(i, "GO");
                break;
            }
        }
        rootObj["techData"] = techDataArray;
      
        // 修改数组对象
        QJsonValue schoolDataValue = rootObj.value("schoolData");
        QJsonArray schoolDataArray = schoolDataValue.toArray();
        for(int i = 0; i < schoolDataArray.size(); i++){
            QJsonObject obj = schoolDataArray.at(i).toObject();
            if(obj.value("schoolName").toString().compare("xiaoxue") == 0){
                obj["schoolCity"] = "Baoji";
                schoolDataArray.replace(i, obj);
                break;
            }
        }
        rootObj["schoolData"] = schoolDataArray;
      
        // 将json数据对象转为字符串
        QJsonDocument document;
        document.setObject(rootObj);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

新增json数据

  • 原始json数据
    •   {
            "id":1002,
            "name":"Tom",
            "techData":["C++", "JAVA", "PYTHON"], 
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"xiaoxue"},
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 新增相应字段后的json数据
    •   {
            "class":5, // 新增项
            "home":{   // 新增项
                "father":52,
                "mather":52
            },
            "id":1002,
            "name":"Tom",
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"xiaoxue"},
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"},
                {"schoolCity":"shanghai","schoolName":"boshi"} // 新增项
            ],
            "scoreData":{
                "Chinese":96,
                "English":82,
                "Math":90,
                "Physics":100 // 新增项
            },
            "sex":true,
            "techData":["C++","JAVA","PYTHON","GO"] //新增GO数据
        }
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"techData\":[\"C++\",\"JAVA\",\"PYTHON\"], \"schoolData\":[{\"schoolCity\":\"Xian\",\"schoolName\":\"xiaoxue\"},{\"schoolCity\":\"Xian\",\"schoolName\":\"zhongxue\"},{\"schoolCity\":\"Beijing\",\"schoolName\":\"daxue\"}],\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true}";
      
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "parse json data failed.";
            return false;
        }
      
        QJsonObject rootObj = rootDoc.object();
      
        // 新增数据
        rootObj.insert("class", 5);
      
        // 新增数据对象
        QJsonObject homeObject;
        homeObject.insert("father", 52);
        homeObject.insert("mather", 52);
        rootObj.insert("home", homeObject);
      
        // 在数据对象中新增数据
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
        scoreDataObj.insert("Physics", 100);
        rootObj["scoreData"] = scoreDataObj;
      
        // 在数组中新增数据
        QJsonValue techDataValue = rootObj.value("techData");
        QJsonArray techDataArray = techDataValue.toArray();
        techDataArray.append("GO");
        rootObj["techData"] = techDataArray;
      
        // 在数组对象中新增数据
        QJsonValue schoolDataValue = rootObj.value("schoolData");
        QJsonArray schoolDataArray = schoolDataValue.toArray();
        QJsonObject doctorObj;
        doctorObj.insert("schoolName", "boshi");
        doctorObj.insert("schoolCity", "shanghai");
        schoolDataArray.append(doctorObj);
        rootObj["schoolData"] = schoolDataArray;
      
      
        QJsonDocument document;
        document.setObject(rootObj);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

删除json数据

  • 原始json数据
    •   {
            "id":1002,
            "name":"Tom", //此项删除
            "techData":["C++","JAVA","PYTHON"], // PYTHON删除 
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"xiaoxue"}, // 此项删除
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "Chinese":96, //此项删除
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 删除相应字段后的json数据
    •   {
            "id":1002,
            "techData":["C++","JAVA"], 
            "schoolData":[
                {"schoolCity":"Xian","schoolName":"zhongxue"},
                {"schoolCity":"Beijing","schoolName":"daxue"}
            ],
            "scoreData":{
                "English":82,
                "Math":90
            },
            "sex":true
        }
      
  • 代码
    •   QByteArray jsonData = "{\"id\":1002,\"name\":\"Tom\",\"techData\":[\"C++\",\"JAVA\",\"PYTHON\"], \"schoolData\":[{\"schoolCity\":\"Xian\",\"schoolName\":\"xiaoxue\"},{\"schoolCity\":\"Xian\",\"schoolName\":\"zhongxue\"},{\"schoolCity\":\"Beijing\",\"schoolName\":\"daxue\"}],\"scoreData\":{\"Chinese\":96,\"English\":82,\"Math\":90},\"sex\":true}";
      
        QJsonParseError result;
        QJsonDocument rootDoc = QJsonDocument::fromJson(jsonData, &result);
        if(rootDoc.isNull() || result.error != QJsonParseError::NoError){
            qDebug() << "rootdoc is null";
            return false;
        }
      
        QJsonObject rootObj = rootDoc.object();
      
        // 删除数据
        rootObj.remove("name");
      
        // 删除数据对象中的数据
        QJsonValue scoreDataValue = rootObj.value("scoreData");
        QJsonObject scoreDataObj = scoreDataValue.toObject();
        scoreDataObj.remove("Chinese");
        rootObj["scoreData"] = scoreDataObj;
      
      
        // 删除数组中的数据
        QJsonValue techDataValue = rootObj.value("techData");
        QJsonArray techDataArray = techDataValue.toArray();
        for(int i = 0; i < techDataArray.size(); i++){
            if(techDataArray.at(i).toString().compare("PYTHON") == 0){
                techDataArray.removeAt(i);
                break;
            }
        }
        rootObj["techData"] = techDataArray;
      
        // 删除数组对象中的数据
        QJsonValue schoolDataValue = rootObj.value("schoolData");
        QJsonArray schoolDataArray = schoolDataValue.toArray();
        for(int i = 0; i < schoolDataArray.size(); i++){
            QJsonObject obj = schoolDataArray.at(i).toObject();
            if(obj.value("schoolName").toString().compare("xiaoxue") == 0){
                schoolDataArray.removeAt(i);
                break;
            }
        }
        rootObj["schoolData"] = schoolDataArray;
      
      
        QJsonDocument document;
        document.setObject(rootObj);
        QByteArray byJsonData = document.toJson(QJsonDocument::Compact);
        QString strJson(byJsonData);
      

你可能感兴趣的:(开发语言,#,QT,qt,json,c++)