• Json格式数据以及QT操作Json数据


    Json数据特点

    Json 是一种数据格式,和语言无关,在什么语言中都可以使用 Json。
    一般处理两方面的任务:

    • 组织数据(数据序列化),用于数据的网络传输。
    • 组织数据(数据序列化),写磁盘文件实现数据的持久化存储(一般以.json 作为文件后缀)。

    Json格式代码样例:

    //test.json
    {
        "Name":"Ace",
        "Sex":"man",
        "Age":20,
        "Family":{
            "Father":"Gol·D·Roger",
            "Mother":"Portgas·D·Rouge",
            "Brother":["Sabo", "Monkey D. Luffy"]
        },
        "IsAlive":false,
        "Comment":"yyds"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Json格式数据的封装与解析

    Json格式数据的封装

    Json格式数据封装参考如下:Json格式数据封装

    Json格式数据的解析

    Json 字符串的解析流程和数据的封装流程相反,假设有这样一个 Json 字符串(字符串中的双引号需要通过转义字符将其转译为普通字符):

    {\"name\":\"luffy\",\"sex\":\"man\",\"age\":19}
    
    
    • 1
    • 2

    实例代码如下:

    #include 
    #include 
    #include 
    #include "cJSON.h"
     
    int main()
    {
        cJSON *json, *name, *sex, *age;
        char* out="{\"name\":\"luffy\",\"sex\":\"man\",\"age\":19}";
     
        json = cJSON_Parse(out); //解析成json形式
        name = cJSON_GetObjectItem(json, "name");  //获取键值内容
        sex = cJSON_GetObjectItem(json, "sex");
        age = cJSON_GetObjectItem(json, "age");
     
        printf("name:%s,sex:%s,age:%d\n", name->valuestring, sex->valuestring, age->valueint);
     
        cJSON_Delete(json);  //释放内存 
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    解析嵌套的 Json 对象

    解析一个嵌套的 Json 对象,数据如下:

    {\"list\":{\"name\":\"luffy\",\"age\":19},\"other\":{\"name\":\"ace\"}}
    
    
    • 1
    • 2
    int main()
    {
        char *s = "{\"list\":{\"name\":\"luffy\",\"age\":19},\"other\":{\"name\":\"ace\"}}";
        cJSON *root = cJSON_Parse(s);
        if(!root) 
        {
            printf("get root faild !\n");
            return -1;
        }
    
        cJSON *js_list = cJSON_GetObjectItem(root, "list");
        if(!js_list) 
        {
            printf("no list!\n");
            return -1;
        }
        printf("list type is %d\n",js_list->type);
    
        cJSON *name = cJSON_GetObjectItem(js_list, "name");
        if(!name) 
        {
            printf("No name !\n");
            return -1;
        }
        printf("name type is %d\n",name->type);
        printf("name is %s\n",name->valuestring);
    
        cJSON *age = cJSON_GetObjectItem(js_list, "age");
        if(!age) 
        {
            printf("no age!\n");
            return -1;
        }
        printf("age type is %d\n", age->type);
        printf("age is %d\n",age->valueint);
    
        cJSON *js_other = cJSON_GetObjectItem(root, "other");
        if(!js_other) 
        {
            printf("no list!\n");
            return -1;
        }
        printf("list type is %d\n",js_other->type);
    
        cJSON *js_name = cJSON_GetObjectItem(js_other, "name");
        if(!js_name) 
        {
            printf("No name !\n");
            return -1;
        }
        printf("name type is %d\n",js_name->type);
        printf("name is %s\n",js_name->valuestring);
    
        if(root)
        {
            cJSON_Delete(root);
        }
        return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    打印结果:

    list type is 6
    name type is 4
    name is luffy
    age type is 3
    age is 19
    list type is 6
    name type is 4
    name is ace
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    解析 Json 数组

    Json 字符串是一个 Json 数组格式:

    {\"names\":[\"luffy\",\"robin\"]}
    
    • 1
    
    int main(int argc, char **argv)
    {
        char *s = "{\"names\":[\"luffy\",\"robin\"]}";
        cJSON *root = cJSON_Parse(s);
        if(!root) 
        {
            printf("get root faild !\n");
            return -1;
        }
        cJSON *js_list = cJSON_GetObjectItem(root, "names");
        if(!js_list)
        {
            printf("no list!\n");
            return -1;
        }
        int array_size = cJSON_GetArraySize(js_list);
        printf("array size is %d\n",array_size);
        for(int i=0; i< array_size; i++) 
        {
            cJSON *item = cJSON_GetArrayItem(js_list, i);
            printf("item type is %d\n",item->type);
            printf("%s\n",item->valuestring);
        }
    
        if(root)
        {
            cJSON_Delete(root);
        }
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    解析嵌套的 Json 对象和数组

    Json 对象和 Json 数组嵌套的形式,下面通过一个例子演示一下应该如何解析,字符串格式如下:

    {\"list\":[{\"name\":\"luffy\",\"age\":19},{\"name\":\"sabo\",\"age\":21}]}
    
    • 1

    在解析的时候,只需要按照从属关系,一层层解析即可:

    • 根节点是一个 Json 对象,基于根节点中的 key 值取出对应的 value 值,得到一个 Json 数组
    • 读出 Json 数组的大小,遍历里边的各个元素,每个元素都是一个 Json 对象
    • 将 Json 对象中的键值对根据 key 值取出对应的 value 值
    • 从取出的 Value 值中读出实际类型对应的数值
    #include "cJSON.h"
    #include 
    #include 
    
    int main(int argc, char **argv)
    {
        char *s = "{\"list\":[{\"name\":\"luffy\",\"age\":19},{\"name\":\"sabo\",\"age\":21}]}";
        cJSON *root = cJSON_Parse(s);
        if(!root) 
        {
            printf("get root faild !\n");
            return -1;
        }
        cJSON *list = cJSON_GetObjectItem(root, "list");
        if(!list)
        {
            printf("no list!\n");
            return -1;
        }
        int array_size = cJSON_GetArraySize(list);
        printf("array size is %d\n",array_size);
        
        for(int i=0; i< array_size; i++) 
        {
            cJSON* item = cJSON_GetArrayItem(list, i);
            cJSON* name = cJSON_GetObjectItem(item, "name");
            printf("name is %s\n",name->valuestring);
            cJSON* age = cJSON_GetObjectItem(item, "age");
            printf("age is %d\n",age->valueint);
        }
    
        if(root)
        {
            cJSON_Delete(root);
        }
        return 0;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    C++中Json数据解析

    援引链接:添加链接描述

    {
      "paramz": {
        "feeds": [
          {
            "id": 299076,
            "oid": 288340,
            "category": "article",
            "data": {
              "subject": "荔枝新闻3.0:不止是阅读",
              "summary": "江苏广电旗下资讯类手机应用“荔枝新闻”于近期推出全新升级换代的3.0版。",
              "cover": "/Attachs/Article/288340/3e8e2c397c70469f8845fad73aa38165_padmini.JPG",
              "pic": "",
              "format": "txt",
              "changed": "2015-09-22 16:01:41"
            }
          }
        ],
        "PageIndex": 1,
        "PageSize": 20,
        "TotalCount": 53521,
        "TotalPage": 2677
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    JSONObject系统自带的解析方式解析,先来JSONObject(系统自带的类)类中的方法:
    在这里插入图片描述
    这里解析类如下:

    public class JsonUtils {
    
        /**
         * 根据json数据解析返回一个List>集合
         * @param json  json数据
         * @return
         */
        public static List<HashMap<String, Object>> getJsonList(String json) {
            List<HashMap<String, Object>> dataList;
            dataList = new ArrayList<>();
            try {
                JSONObject rootObject = new JSONObject(json);
                JSONObject paramzObject = rootObject.getJSONObject("paramz");
                JSONArray feedsArray = paramzObject.getJSONArray("feeds");
                for (int i = 0; i < feedsArray.length(); i++) {
                    JSONObject sonObject = feedsArray.getJSONObject(i);
                    JSONObject dataObject = sonObject.getJSONObject("data");
                    String subjectStr = dataObject.getString("subject");
                    String summaryStr = dataObject.getString("summary");
                    String coverStr = dataObject.getString("cover");
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("subject", subjectStr);
                    map.put("summary", summaryStr);
                    map.put("cover", coverStr);
                    dataList.add(map);
                }
                return dataList;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    此方法写起来主要是比较费时间,就是几个方法不停的调用。

    Qt 中 Json 的读写操作

    写入writeJson()数据

    
    void MainWindow::writeJson()
    {
    
            QJsonObject obj;
            obj.insert("Name", "Ace");
            obj.insert("Sex", "man");
            obj.insert("Age", 20);
    
            QJsonObject subObj;
            subObj.insert("Father", "Gol·D·Roger");
            subObj.insert("Mother", "Portgas·D·Rouge");
            QJsonArray array;
            array.append("Sabo");
            array.append("Monkey D. Luffy");
            subObj.insert("Brother", array);
            obj.insert("Family", subObj);
            obj.insert("IsAlive", false);
            obj.insert("Comment", "yyds");
    
            QJsonDocument doc(obj);
            QByteArray json = doc.toJson();
    
            QFile file("D:/Qt/QTT/AI/TcpServer/ace.json");
            file.open(QFile::WriteOnly);
            file.write(json);
            file.close();
    
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    测试结果如下

    在这里插入图片描述

    读取readJson()数据

    
    void MainWindow::readJson()
    {
        QFile file("D:/Qt/QTT/AI/TcpServer/ace.json");
        file.open(QFile::ReadOnly);
        QByteArray json = file.readAll();
        file.close();
    
        QJsonDocument doc = QJsonDocument::fromJson(json);
        if(doc.isObject())
        {
            QJsonObject obj = doc.object();
            QStringList keys = obj.keys();
            for(int i=0; i<keys.size(); ++i)
            {
                QString key = keys.at(i);
                QJsonValue value = obj.value(key);
                if(value.isBool())
                {
                    qDebug() << key << ":" << value.toBool();
                }
                if(value.isString())
                {
                    qDebug() << key << ":" << value.toString();
                }
                if(value.isDouble())
                {
                    qDebug() << key << ":" << value.toInt();
                }
                if(value.isObject())
                {
                    qDebug()<< key << ":";
                    // 直接处理内部键值对, 不再进行类型判断的演示
                    QJsonObject subObj = value.toObject();
                    QStringList ls = subObj.keys();
                    for(int i=0; i<ls.size(); ++i)
                    {
                        QJsonValue subVal = subObj.value(ls.at(i));
                        if(subVal.isString())
                        {
                            qDebug() << "   " << ls.at(i) << ":" << subVal.toString();
                        }
                        if(subVal.isArray())
                        {
                            QJsonArray array = subVal.toArray();
                            qDebug() << "   " << ls.at(i) << ":";
                            for(int j=0; j<array.size(); ++j)
                            {
                                // 因为知道数组内部全部为字符串, 不再对元素类型进行判断
                                qDebug() << "       " << array[j].toString();
                            }
                        }
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    测试结果如下:

    在这里插入图片描述

  • 相关阅读:
    Python 常用模块(一):时间模块
    VINS中的重力-尺度-速度初始化(2)
    牛客小白月赛55 A-E 回顾
    淘宝营业执照升级流程是什么?营业执照怎么获取?
    如何隐藏自己的代码(很酷)
    【工程应用八】终极的基于形状匹配方案解决(小模型+预生成模型+无效边缘去除+多尺度+各项异性+最小组件尺寸)
    【电力系统】基于YALMIP 的微网(光伏+风电+蓄电池+微电网+柴油机)优化调度模型附matlab代码
    ajax、promise封装ajax、axios
    聊聊分布式架构08——SpringBoot开启微服务时代
    华为乾坤区县教育安全云服务解决方案(2)
  • 原文地址:https://blog.csdn.net/m0_46152793/article/details/126133364