使用Qt读写JSON(二)——从文件解析JSON

2018-12-19  本文已影响2人  若梦儿

之前介绍了简单的示例,这次我们进行JSON文件的解析。
在你的桌面新建文件命名为test.json,内容填写如下:

{
    "postsNum" : 2,
    "posts" : [
        {
            "postID" : 10086,
            "postTitle" : "hello",
            "postContent" : "你好啊"
        },
        {
            "postID" : 10010,
            "postTitle" : "hi",
            "postContent" : "大家好"
        }
    ]
}

从JSON定义来看,这是一个包含有两个键值对的对象,其中一个对象的名字是"postsNum",值是一个数字,另一键值对的名字是"posts",值是一个数组。这个数组由两个对象组成,每个对象由三个相同的键值对组成,第一个键值对名字为"postID" ,值为数字;第二个键值对名字为 "postTitle" ,值为字符串 "hello";第三个键值对名字为 "postContent" ,值为字符串。实际上,数组中的对象描述了一个简单的帖子的数据结构,这个帖子有postID、postTitle、postContent组成。

接下来我们使用Qt Creator新建一个Qt Console Application项目,名称和位置可以随意。

修改默认生成的main.cpp中的代码如下所示:

#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>

#include <QSysInfo>

#include <cstdlib>
#include <iostream>

using std::cout;

int main( int argc, char *argv[] ) {
    // Qt的一个宏,消除未使用变量的警告,无实际作用
    // 定义为,#define Q_UNUSED(x) (void)x
    Q_UNUSED( argc );
    Q_UNUSED( argv );

    // 如果当前操作系统为windows系统的话
    // 修改控制台的编码为utf8,防止中文乱码
    if ( QSysInfo::productType() == "windows" ||
         QSysInfo::productType() == "winrt" ) {
        system( "chcp 65001" );
    }

    cout << "当前使用的操作系统类型为:";
    cout << QSysInfo::productType().toStdString() << "\n";
    // 默认打开的文件位置为用户桌面的test.txt文件。
    QFile file( QDir::homePath() + "/Desktop/test.json" );
    if ( !file.open( QIODevice::ReadWrite ) ) {
        cout << "文件打开失败!\n";
        exit( 1 );
    }
    cout << "文件打开成功\n";

    QJsonParseError jsonParserError;
    QJsonDocument   jsonDocument =
        QJsonDocument::fromJson( file.readAll(), &jsonParserError );

    if ( !jsonDocument.isNull() &&
         jsonParserError.error == QJsonParseError::NoError ) {
        cout << "文件解析成功\n";
        if ( jsonDocument.isObject() ) {
            QJsonObject jsonObject = jsonDocument.object();
            if ( jsonObject.contains( "postsNum" ) &&
                 jsonObject.value( "postsNum" ).isDouble() ) {
                cout << "postsNum is " << jsonObject.value( "postsNum" ).toInt()
                     << "\n";
            }

            if ( jsonObject.contains( "posts" ) &&
                 jsonObject.value( "posts" ).isArray() ) {
                QJsonArray jsonArray = jsonObject.value( "posts" ).toArray();
                for ( int i = 0; i < jsonArray.size(); i++ ) {
                    if ( jsonArray[ i ].isObject() ) {
                        QJsonObject jsonObjectPost = jsonArray[ i ].toObject();
                        if ( jsonObjectPost.contains( "postID" ) &&
                             jsonObjectPost.contains( "postTitle" ) &&
                             jsonObjectPost.contains( "postContent" ) &&
                             jsonObjectPost.value( "postID" ).isDouble() &&
                             jsonObjectPost.value( "postTitle" ).isString() &&
                             jsonObjectPost.value( "postContent" )
                                 .isString() ) {
                            cout << "posts[" << i << "] :\n";
                            cout << "postID is "
                                 << jsonObjectPost.value( "postID" ).toInt()
                                 << "\n";
                            cout << "postTitle is "
                                 << jsonObjectPost.value( "postTitle" )
                                        .toString()
                                        .toStdString()
                                 << "\n";
                            cout << "postContent is "
                                 << jsonObjectPost.value( "postContent" )
                                        .toString()
                                        .toStdString()
                                 << "\n";
                        }
                    }
                }
            }
        }
    }

    file.close();
    cout << "按任意键退出程序\n";

    return 0;
}


这段代码也很容易理解,首先判断当前系统是否为windows,如果是的话就修改CMD编码为utf8,防止出现中文乱码,之后打开桌面上的test.json文件,解析为json文件并输出里面的数据。

上一篇 下一篇

猜你喜欢

热点阅读