QT 解析JSon字符串

来源:互联网 发布:淘宝手机端图片加链接 编辑:程序博客网 时间:2024/06/06 22:01
  1. 解析如下图所示JSON
    这里写图片描述

  2. 代码如下图

#include "mainwindow.h"#include <QApplication>#include <QDebug>#include <QJsonDocument>#include <QJsonArray>#include <QJsonObject>#include <QDebug>#include <QObject>bool MakePrtMsg(QJsonObject PrintMsg){        /* 解析传入数据 */        QJsonObject jo = PrintMsg;        /* 1.获取数据 */        QString shop_id = jo["shop_id"].toString();        qDebug() << "商户号: " + shop_id;        /* 2.获取Json嵌套 */        //QJsonValue value = jo.value("buy_items");           //获取value        //QJsonArray buy_items = value.toArray();             //value转换        QJsonArray buy_items = jo.["buy_items"].toArray;        for(int i=0; i<buy_items.size(); i++)        {            QJsonValue value1 = buy_items.at(i);            QJsonObject item = value1.toObject();            QString title = item["title"].toString();            qDebug() << "title: " + title;        }}int main(int argc, char *argv[]){    QApplication a(argc, argv);    MainWindow w;    QString t = QObject::tr("{") + \                    "\"retflag\":\"0\","  + \                    "\"TXTString\":" + \                    "{" + \                        "\"buy_items\":" + \                        "[" + \                            "{\"title\":\"生鲜1元\"}," + \                            "{\"title\":\"生鲜2元\"}" + \                         "]" + \                    "}," + \                    "\"total\":100" + \                 "}";    qDebug() << t;    QByteArray buf = t.toUtf8();    QJsonDocument jd = QJsonDocument::fromJson(buf);    if(jd.isObject())    {        QJsonObject jo = jd.object();        /* 打印商品信息 */        //QJsonValue value = jo.value("TXTString");        //QJsonObject PrintMsg = value.toObject();    QJsonObject jo.["TXTString"].toObject();        MakePrtMsg(PrintMsg);     }    w.show();    return a.exec();}
原创粉丝点击