qt Jsoncpp的指定目录生成json并解析

86 篇文章 1 订阅

在qt中使用jsoncpp的详细方法如下:
1、下载jsoncpp。下载地址
2、在qt中打开jsoncpp项目,然后编译一份debug的库文件和一份release的库文件。
在这里插入图片描述
在这里插入图片描述
3、新建测试项目,并且在测试项目目录下新建一个lib目录,在pro文件中添加配置:

win32:CONFIG(release, debug|release): LIBS += -L$$PWD/lib/release/ -lJsoncpp
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/lib/debug/ -lJsoncpp

INCLUDEPATH += $$PWD/lib/debug
DEPENDPATH += $$PWD/lib/debug

4、指定一个目录生成json文件,需要使用到回调进行判断是文件夹还是文件。

//将一个目录结构生成一个json文件
void MJson::startJsonFile()
{
    QFileInfo dirinfo(m_jsonDirPath);
    Json::Value root;
    Json::Value obj;
    obj["filename"] = dirinfo.fileName().toUtf8().data();
    obj["filesize"] = QString("%1").arg(dirinfo.size()).toUtf8().data();
    obj["filepath"] = dirinfo.filePath().toUtf8().data();
    if (dirinfo.isDir())
        obj["filetype"] = 1;
    else if (dirinfo.isFile())
        obj["filetype"] = 2;
#if 1
    //方法1
    Json::Value child;
    getDirFile1(child,m_jsonDirPath); //生成json
    obj["child"] = Json::Value(child);
    //方法2
//    getDirFile1(obj["child"],m_jsonDirPath);//生成json
#else
    //方法3
    Json::Value child;
    child = getDirFile(m_jsonDirPath);//生成json
    obj["child"] = Json::Value(child);
#endif
    root["root"] = Json::Value(obj);

    //缩进输出
    Json::StyledWriter sw;
    //输出到文件
    QFile file("demo.json");
    file.open(QIODevice::WriteOnly);
    file.write(sw.write(root).c_str());
}

Json::Value MJson::getDirFile(QString dirpath)
{
    Json::Value parent;
    QDir dir(dirpath);
    foreach (QFileInfo info, dir.entryInfoList())
    {
        if (info.fileName()=="."||info.fileName()=="..")
            continue;
        Json::Value obj;
        obj["filename"] = info.fileName().toUtf8().data();
        obj["filesize"] = QString("%1").arg(info.size()).toUtf8().data();
        obj["filepath"] = info.filePath().toUtf8().data();
        if (info.isFile())
        {
            obj["filetype"] = 2;
            parent.append(obj);
        }
        else if (info.isDir())
        {
            obj["filetype"] = 1;
            obj["child"] = Json::Value(getDirFile(info.filePath()));//递归
            parent.append(obj);
        }
    }
    return parent;
}

void MJson::getDirFile1(Json::Value& parent,QString dirpath)
{
    QDir dir(dirpath);
    foreach (QFileInfo info, dir.entryInfoList())
    {
        if (info.fileName()=="."||info.fileName()=="..")
            continue;
        Json::Value obj;
        obj["filename"] = info.fileName().toUtf8().data();
        obj["filesize"] = QString("%1").arg(info.size()).toUtf8().data();
        obj["filepath"] = info.filePath().toUtf8().data();
        if (info.isFile())
        {
            obj["filetype"] = 2;
            parent.append(obj);
        }
        else if (info.isDir())
        {
            obj["filetype"] = 1;
#if 1
            //方法1
            Json::Value child;
            getDirFile1(child,info.filePath());//递归
            obj["child"] = child;
#else
            //方法2
            getDirFile1(obj["child"],info.filePath());//递归
#endif
            parent.append(obj);
        }
    }
}

5、生成json文件后,就需要解析了,为了方便观察,这边将目录结构使用QTreeWidget具象化。
在这里插入图片描述
json文件:

{
   "root" : {
      "child" : [
         {
            "filename" : "1.txt",
            "filepath" : "E:/work/codetest/webYunpan/test/1.txt",
            "filesize" : "0",
            "filetype" : 2
         },
         {
            "filename" : "2.txt",
            "filepath" : "E:/work/codetest/webYunpan/test/2.txt",
            "filesize" : "0",
            "filetype" : 2
         },
         {
            "child" : [
               {
                  "filename" : "11.txt",
                  "filepath" : "E:/work/codetest/webYunpan/test/s/11.txt",
                  "filesize" : "0",
                  "filetype" : 2
               },
               {
                  "child" : [
                     {
                        "filename" : "111.txt",
                        "filepath" : "E:/work/codetest/webYunpan/test/s/ss/111.txt",
                        "filesize" : "0",
                        "filetype" : 2
                     },
                     {
                        "filename" : "222.txt",
                        "filepath" : "E:/work/codetest/webYunpan/test/s/ss/222.txt",
                        "filesize" : "0",
                        "filetype" : 2
                     },
                     {
                        "child" : [
                           {
                              "filename" : "1111.txt",
                              "filepath" : "E:/work/codetest/webYunpan/test/s/ss/sss/1111.txt",
                              "filesize" : "0",
                              "filetype" : 2
                           },
                           {
                              "child" : null,
                              "filename" : "ssss",
                              "filepath" : "E:/work/codetest/webYunpan/test/s/ss/sss/ssss",
                              "filesize" : "0",
                              "filetype" : 1
                           }
                        ],
                        "filename" : "sss",
                        "filepath" : "E:/work/codetest/webYunpan/test/s/ss/sss",
                        "filesize" : "0",
                        "filetype" : 1
                     }
                  ],
                  "filename" : "ss",
                  "filepath" : "E:/work/codetest/webYunpan/test/s/ss",
                  "filesize" : "0",
                  "filetype" : 1
               }
            ],
            "filename" : "s",
            "filepath" : "E:/work/codetest/webYunpan/test/s",
            "filesize" : "0",
            "filetype" : 1
         }
      ],
      "filename" : "test",
      "filepath" : "E:/work/codetest/webYunpan/test",
      "filesize" : "0",
      "filetype" : 1
   }
}

解析代码:

void MJson::slotAnalyJson()
{
   //删除上一次生成的树状结构
    if (m_treeWidget->topLevelItemCount()>0)
    {
        QTreeWidgetItem* rootItem = m_treeWidget->topLevelItem(0);
        int itemChildrenCounts = rootItem->childCount();
        while(itemChildrenCounts--)
        {
            QTreeWidgetItem * child = rootItem->child(itemChildrenCounts);
            child->removeChild(child);
            delete child;
            child = nullptr;
        }
        m_treeWidget->clear();
    }
    Json::Reader reader;
    Json::Value root;
    QFile file("demo.json");  //使用QFile获取json文件内容
    file.open(QIODevice::ReadOnly);
    if (!reader.parse(file.readAll().data(),root))//将json数据绑定到reader上
    {
        QMessageBox::information(this,"title","open demo.json failed");
        return;
    }
    //最上层文件夹信息
    Json::Value obj = root["root"];
    QString filename = QString::fromUtf8(obj["filename"].asString().c_str());
    QString filesize = QString::fromUtf8(obj["filesize"].asString().c_str());
    QString filepath = QString::fromUtf8(obj["filepath"].asString().c_str());
    int filetype = obj["filetype"].asInt();
    //创建根节点
    QTreeWidgetItem* rootitem = new QTreeWidgetItem(QStringList()<<filename);
    m_treeWidget->addTopLevelItem(rootitem);
    rootitem->setToolTip(0,filepath);
    m_treeWidget->setStyleSheet("QTreeWidget{background-color: #5B677A;font-size:17px;color: white;}"
                                "QTreeWidget::item{margin:13px;background: #5B677A;background-clip: margin;}"
                                "QTreeWidget::branch:!has-children:has-siblings:adjoins-item{border-image:none;image:url(:/file.jpeg);}"
                                "QTreeWidget::branch:!has-children:!has-siblings:adjoins-item{border-image:none;image:url(:/file.jpeg);}"
                                "QTreeWidget::branch:closed:has-children:!has-siblings,"
                                "QTreeWidget::branch:closed:has-children:has-siblings {border-image: none;image: url(:/dir.jpeg);}"
                                "QTreeWidget::branch:open:has-children:!has-siblings,"
                                "QTreeWidget::branch:open:has-children:has-siblings{border-image: none;image: url(:/dir.jpeg);}");
    //解析                                
    analyDirfile(obj,rootitem);
}
//递归方法读取json节点
void MJson::analyDirfile(Json::Value& parent,QTreeWidgetItem* parentItem)
{
    Json::Value child = parent["child"];
    for (int i = 0;i < child.size();i++)
    {
        Json::Value childObj = child[i];
        QString filename = QString::fromUtf8(childObj["filename"].asString().c_str());
        QString filesize = QString::fromUtf8(childObj["filesize"].asString().c_str());
        QString filepath = QString::fromUtf8(childObj["filepath"].asString().c_str());
        int filetype = childObj["filetype"].asInt();
        //创建一个子节点
        QTreeWidgetItem* item = new QTreeWidgetItem(parentItem);
        item->setText(0,filename);
        item->setToolTip(0,filepath);
        item->setExpanded(true);
        //递归
        analyDirfile(childObj,item);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东方忘忧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值