有关如何读取,写入和打印QJson代码的最小示例(使用QJsonDocument,QJsonArray,QJsonObject和QFile) [英] Minimal Example on how to read, write and print QJson code (with QJsonDocument, QJsonArray, QJsonObject, QFile)

查看:157
本文介绍了有关如何读取,写入和打印QJson代码的最小示例(使用QJsonDocument,QJsonArray,QJsonObject和QFile)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个最小的完整的可执行qt或c ++代码示例来解析和编写此Json代码:

I am searching for a minimal full executable qt or c++ code example to parse and write this Json code:

{
    "FirstName": "John",
    "LastName": "Doe",
    "MiddleName": null,
    "Age": 43,

    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "Phone numbers": [
        "+44 1234567",
        "+44 2345678"
    ]
    "Valid":true,
}

  • 上面的示例由一个具有5个键/值对的对象组成.其中两个值是字符串,一个是数字,
  • 一个是另一个对象,最后一个是数组.
  • 有效的JSON文档是数组或对象,因此文档始终以方括号或大括号开头.
    • Json有还有2个键/值对-值'null'和'布尔'
    • Json has 2 more key/value pairs - value 'null' and 'bool'

    是的,我看到了保存游戏示例" 并试图找出答案.

    And yes, I have seen a "Save Game Example" and tried to figure it out.

    但是将近一周之后,我放弃了将没有枚举,QVectors和3个不同的头文件的最小Example转移到我的项目中,以处理代码段.无关紧要的是小部件还是核心代码.

    But after nearly a week I gave up to transfer a minimal Example without enums, QVectors and 3 different header Files over to my project to handle the code snippet. Doesn't matter if its for a widget or core code.

    我已经成功地完成了xml读写程序,但是似乎我错过了一些重要的要点,并且得到了与解析可能或不一定有关的json错误.如果没有最少的完全可以运行的代码示例,我将无法排除它.

    I already did a xml read and write program successfully but it seems I miss some Important point and get errors with json that may or may not have to do with the parsing. I am not able to rule it out without a minimal fully working code example.

    所以我的问题是:能否请您提供一个编写,读取和打印Json文件的最小示例?谢谢你.

    推荐答案

    我想它也可能对其他人有帮助,我想通了, 感谢@Botje的榜样,这确实有所帮助. 通常,我很容易记得将数据表示为QByteArray 在内存中.

    I guess it might help someone else too, I figured it all out, thanks to @Botje for his example, really helped. In general it is easy for me to remember to represent data as QByteArray in the memory.

    欢迎访问并使用存储在json文件中的每个单个值的最小示例:

    A minimal example to access and also use every single value stored in a json file, you are welcome:

    (是的,我本可以将其编写得更加紧凑,但是我想这会使它更容易理解,因此为了可读性,我省去了函数/类/结构.)

    #include <QCoreApplication>
    #include <QString>
    #include <QVariant>
    #include <QFile>
    #include <QByteArray>
    #include <QTextStream>
    #include <QDebug>
    
    //json specific
    #include <QJsonParseError>
    #include <QJsonDocument>
    #include <QJsonArray>
    #include <QJsonObject>
    #include <QJsonParseError>
    #include <QJsonValue>
    
    
        void writeJsonFile();
        void readJsonFile();
    
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        writeJsonFile();
        readJsonFile();
    
        return a.exec();
    }
    
    void writeJsonFile()
    {
        qDebug() << "Write Json File: ";
    
        //1. Create a QJsonObject and add values to it
        QJsonObject jsonObj;
        jsonObj["FirstName"] = "John";
        //no value will be written as null in the json file
        jsonObj["MiddleName"];
        jsonObj["LastName"] = "Doe";
        jsonObj["Age"] = 43;
    
        //2. Create Item of Json Object content (object of object)
        QJsonObject jsonItemObj;
        jsonItemObj["Street"] = "Downing Street 10";
        jsonItemObj["City"] = "London";
        jsonItemObj["Country"] = "Great Britain";
        //3. Add jsonItemObj to jsonObj and give it an object Name
        jsonObj["Address"] = jsonItemObj;
    
        //4. Create jsonArray and fill it with values - similar to filling a vector
        QJsonArray jsonArray;
        jsonArray.append("+44 1234567");
        jsonArray.append("+44 2345678");
    
        //Add a bool to the Object
        jsonObj["Valid"] = true;
    
        //5. Add jsonArray to jsonObj and give it an object Name
        jsonObj["Phone numbers"] = jsonArray;
        //(It can also be added to the jsonItemObj to be inline with the Address section)
        //with jsonItemObj["Phone numbers"] = jsonArray or as much objects of objects
        //you need
    
    
        /* As I understood it, most Qt classes use a QByteArray to handle data internally
         * because it is really fast/efficient,
         * also QFile QIODevice, it is a good idea to hold the read/write
         * QIODevice data as QByteArray in the Memory
         */
    
        //6. Create a QByteArray and fill it with QJsonDocument (json formatted)
        QByteArray byteArray;
        byteArray = QJsonDocument(jsonObj).toJson();
    
        //7. Open a QFile and write the byteArray filled with json formatted data
        //thanks to the QJsonDocument() Class to the file
        QFile file;
        file.setFileName("file.json");
        if(!file.open(QIODevice::WriteOnly)){
            qDebug() << "No write access for json file";
            return;
        }
    
        //8. finally write the file and close it
        file.write(byteArray);
        file.close();
    
        //9. Print out the byteArray to the terminal
        QTextStream textStream(stdout);
        textStream << "Rendered json byteArray text: " << endl;
        textStream << byteArray << endl;
    }
    
    void readJsonFile()
    {
        qDebug() << "Read Json File:";
    
        //1. Open the QFile and write it to a byteArray and close the file
        QFile file;
        file.setFileName("file.json");
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "Json filef couldn't be opened/found";
            return;
        }
    
        QByteArray byteArray;
        byteArray = file.readAll();
        file.close();
    
        //2. Format the content of the byteArray as QJsonDocument
        //and check on parse Errors
        QJsonParseError parseError;
        QJsonDocument jsonDoc;
        jsonDoc = QJsonDocument::fromJson(byteArray, &parseError);
        if(parseError.error != QJsonParseError::NoError){
            qWarning() << "Parse error at " << parseError.offset << ":" << parseError.errorString();
            return;
        }
    
        //3. Create a jsonObject and fill it with the byteArray content, formatted
        //and holding by the jsonDocument Class
        QJsonObject jsonObj;
        jsonObj = jsonDoc.object();
    
        //4. Now picking the jsonValues and printing them out or do what ever you need
        QJsonValue jsonVal;
        QTextStream textStream(stdout);
    
        jsonVal = jsonObj.value("FirstName");
        textStream << jsonVal.toString() << endl;
    
        jsonVal = jsonObj.value("MiddleName");
        //null gets back to an empty fild - added the sting "null/empty" to make it visible
        textStream << jsonVal.toVariant().toString() << "null/empty" << endl;
    
        jsonVal = jsonObj.value("LastName");
        textStream << jsonVal.toString() << endl;
    
        //The number has to be converted to an int and than to a string to print it
        jsonVal = jsonObj.value("Age");
        textStream << QString::number(jsonVal.toInt()) << endl;
    
        //5. Now we need to fill the object of the object. To do that, we need
        //the Item Object and a jsonSubVal object for json without a loop
        QJsonObject jsonItemObj;
        QJsonValue jsonSubVal;
    
        jsonVal = jsonObj.value(QString("Address"));
        jsonItemObj = jsonVal.toObject();
    
           jsonSubVal = jsonItemObj["Street"];
           textStream << jsonSubVal.toString() << endl;
    
           jsonSubVal = jsonItemObj["City"];
           textStream << jsonSubVal.toString() << endl;
    
           jsonSubVal = jsonItemObj["Country"];
           textStream << jsonSubVal.toString() << endl;
    
        //6. now the Phone Numbers array with a loop
        QJsonArray jsonArray;
        jsonArray = jsonObj["Phone numbers"].toArray();
    
        for(int i = 0; i < jsonArray.size(); i++)
            textStream << jsonArray[i].toString() << endl;
    
        textStream << "or with foreach" << endl;
    
        foreach(QJsonValue v, jsonArray)
            textStream << v.toString() << endl;
    
        //7. And finally the bool value:
        jsonVal = jsonObj.value(QString("Valid"));
        textStream << jsonVal.toVariant().toString() << endl;
    
        textStream << "or as number, not a string: ";
    
        textStream << (QString::number(jsonVal.toInt())) << endl;
    
        textStream << "\nThe whole file as printed in the file \n" <<
                      jsonDoc.toJson(QJsonDocument::Indented);
    
    
    
    

    这篇关于有关如何读取,写入和打印QJson代码的最小示例(使用QJsonDocument,QJsonArray,QJsonObject和QFile)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆