如何移植和使用QJson?

一、QJson庫的下載

      下載鏈接   http://qjson.sourceforge.net/build/

二、使用Qt4.8+Mingw編譯QJson

1、解壓QJson-master壓縮包,新建一個QJson目錄,將QJson-master中的include 和src目錄拷貝到QJson目錄下。

然後,再QJson目錄下創建一個qjson.pro的項目文件,在文件中編寫如下內容:

TARGET = qjson

TEMPLATE = lib
CONFIG += shared
CONFIG += dll

#QMAKE_CXXFLAGS += -fexceptions
CONFIG += exceptions

DEFINES += QJSON_MAKEDLL

#Mingw
win32-g++{
    BINDIR = ../win32-gcc-bin
}

#Vs2010
#win32-msvc2010{
#    BINDIR = ../../vs2010-bin
#}

##arm-linux
#linux-arm-g++{
#    BINDIR = ../arm-linux-gcc-bin
#
#    DEFINES += __NO_PRECOMPILED_HEADER__
#    DEFINES += _TTY_POSIX_
#}

#CONFIG(debug, debug|release){
#    DESTDIR = $$BINDIR/debug
#}else{
#    DESTDIR = $$BINDIR/release
#}

SOURCES += \

HEADERS +=\

    

然後使用Qt4.8.3打開項目工程文件qjson.pro,在項目樹上,添加現有文件,將include和src目錄下的文件添加到qjson項目中,構建工程,正常可生成qjson.dll庫文件。

三、QJson項目測試

1、新建一個Qt控制檯項目 — testQjson ,在pro文件中鏈接qjson動態庫。將qjson的include目錄拷貝到當前測試項目目錄下。可以將頭文件添加到項目中,也可以不用添加。

#-------------------------------------------------
#
# Project created by QtCreator 2020-05-15T08:29:29
#
#-------------------------------------------------

QT       += core

QT       -= gui

TARGET = testQjson
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

DEFINES += QJSON_MAKEDLL
SOURCES += main.cpp \
    include/person.cpp

LIBS += -L$$PWD/release/bin/ -lqjson
INCLUDEPATH += $$PWD/release/bin
DEPENDPATH += $$PWD/release/bin

HEADERS += \
    include/FlexLexer.h \
    include/json_parser.hh \
    include/json_scanner.h \
    include/location.hh \
    include/parser.h \
    include/parser_p.h \
    include/parserrunnable.h \
    include/position.hh \
    include/qjson_debug.h \
    include/qjson_export.h \
    include/qobjecthelper.h \
    include/serializer.h \
    include/serializerrunnable.h \
    include/stack.hh \
    include/person.h

然後我們添加一個cpp類如下:

// person.h

#ifndef PERSON_H
#define PERSON_H

#include <QObject>

#include <QDate>
#include <QVariantMap>
#include <QDebug>
#include <QString>

class Person : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString name READ name WRITE setName)
    Q_PROPERTY(int phoneNumber READ phoneNumber WRITE setPhoneNumber)
    Q_PROPERTY(Gender gender READ gender WRITE setGender)
    Q_PROPERTY(QDate dob READ dob WRITE setDob)
    Q_ENUMS(Gender)
public:
   Person(QObject* parent = 0);
   ~Person();

   QString name() const;
   void setName(const QString& name);

   int phoneNumber() const;
   void setPhoneNumber(const int  phoneNumber);

   enum Gender {Male, Female};
   void setGender(Gender gender);
   Gender gender() const;

   QDate dob() const;
   void setDob(const QDate& dob);

 public:
   QString m_name;
   int m_phoneNumber;
   Gender m_gender;
   QDate m_dob;
};


#endif // PERSON_H

 

// person.cpp

#include "person.h"

Person::Person(QObject *parent) : QObject(parent)
{

}


Person::~Person(){}

QString Person::name() const
{
    return m_name;
}

void Person::setName(const QString &name)
{
    m_name = name;
}

int Person::phoneNumber() const
{
    return m_phoneNumber;
}

void Person::setPhoneNumber(const int phoneNumber)
{
    m_phoneNumber = phoneNumber;
}

void Person::setGender(Person::Gender gender)
{
    m_gender = gender;
}

Person::Gender Person::gender() const
{
    return m_gender;
}

QDate Person::dob() const
{
    return m_dob;
}

void Person::setDob(const QDate &dob)
{
    m_dob = dob;
}

 

在main.cpp 文件中,我們使用QJson中幾種不同的方式來生成Json字符串和解析Json字符串。

#include <QCoreApplication>

#include "../../include/parser.h"
#include "../../include/qobjecthelper.h"
#include "../../include/serializer.h"
#include "../../include/person.h"

using namespace QJson;

typedef struct {
    QString name;
    int age;
}student_t;

Q_DECLARE_METATYPE(student_t)



int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    /**一 、[將特定類中的成員變量保存在json字符串中],個人感覺其優點也是其缺點,不夠靈活***********************/
    // 組成json格式 ==》 class類型
    Person person;
    person.setName("Flavio");
    person.setPhoneNumber(123456);
    person.setGender(Person::Male);
    person.setDob(QDate(1982, 7, 12));

    QVariantMap variant = QJson::QObjectHelper::qobject2qvariant(&person);
    QJson::Serializer serializer;
    QByteArray json_string =  serializer.serialize( variant);
    qDebug() << json_string;

    // "{ "dob" : "1982-07-12", "gender" : 0, "name" : "Flavio", "phoneNumber" : 123456 }"

    // json字符串解析
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(json_string, &ok).toMap();
    if (!ok) {
        qFatal("An error occurred during parsing");
        exit (1);
    }

    qDebug() << "dob:" << result["dob"].toString()
             << "  gender:" << result["gender"].toInt()
             << "  name:" << result["name"].toString()
             << "  phoneNumber:" << result["phoneNumber"].toInt();



    /**二、簡單的json字符串生成*************************************/
    // json字符串生成==》 自定義類型1:
    student_t student = {"zhangshan",20};
    QVariantMap v_st;
    v_st.insert("name",student.name);
    v_st.insert("age",student.age);
    qDebug() << serializer.serialize( v_st);
    /*****************************************************************************************/

    /**三、複雜的json字符串生成****************************************************/

    // parser complex json string
    /*
     * QString json("{"
                 "\"encoding\" : \"UTF-8\","
                 "\"plug-ins\" : [\"python\",\"c++\",\"ruby\"],"
                 "\"types\":[{\"A\":1,\"B\":5},{\"A\":2,\"B\":6}],"
                 "\"indent\" : { \"length\" : 3, \"use_space\" : true }"
                 "}");
    */
    /// json字符串生成
    QVariantMap js_t;
    js_t.insert("encoding","UTF-8");

    /// 添加json對象
    QVariantMap indent_map;
    indent_map.insert("length",3);
    indent_map.insert("use_space",true);
    js_t.insert("indent",indent_map);


    /// 添加json數組對象1
    QVariantList plug_ins_list;
    plug_ins_list << "python" << "c++" << "ruby";
    js_t.insert("plug-ins",plug_ins_list);

    /// 添加json數組對象1
    QVariantList type_list;
    QVariantMap map1;
    map1.insert("A",1);
    map1.insert("B",5);

    QVariantMap map2;
    map2.insert("A",2);
    map2.insert("B",6);
    type_list << map1 << map2;
    js_t.insert("types",type_list);

    qDebug() << "***************************************************";
    QString json = serializer.serialize( js_t);
    qDebug() << json;
    qDebug() << "***************************************************";


    /// 此json字符串的解析
    result = parser.parse(json.toUtf8(), &ok).toMap();
    if (!ok) {
        qFatal("An error occurred during parsing");
        exit (1);
    }

    qDebug() << "json:" << result;

    /*   通過這裏的打印結果,其實可以逆向驗證我們使用QJson組成對象的方法是否正確
     *
     QMap( 
          ("encoding", QVariant(QString, "UTF-8") )
          ( "indent" ,  QVariant(QVariantMap, QMap(("length",   QVariant(qulonglong, 3) )
          ( "use_space" ,  QVariant(bool, true) ) )  ) )
          ( "plug-ins" ,  QVariant(QVariantList, (QVariant(QString, "python") ,  QVariant(QString, "c++") ,  QVariant(QString, "ruby") )  ) )
          ( "types" , 
                  QVariant(QVariantList, 
                          (
                            QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 1) ) ( "B" ,  QVariant(qulonglong, 5) ) )  ) , 
                            QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 2) ) ( "B" ,  QVariant(qulonglong, 6) ) )  ) )
                          ) 
         ) 
       )
    */


    qDebug() << "encoding:" << result["encoding"].toString();
    qDebug() << "plugins:";

    foreach (QVariant plugin, result["plug-ins"].toList()) {
        qDebug() << "\t-" << plugin.toString();
    }

    qDebug() << result["types"];
    foreach (QVariant type, result["types"].toList()) {
        qDebug() << "type:" << type;
        QVariantMap ret = type.toMap();
        qDebug() << "A:" << ret["A"].toInt() << "  B:" << ret["B"].toInt();
    }

    QVariantMap nestedMap = result["indent"].toMap();
    qDebug() << "length:" << nestedMap["length"].toInt();
    qDebug() << "use_space:" << nestedMap["use_space"].toBool();


    return a.exec();
}

打印輸出結果如下:

{ "dob" : "1982-07-12", "gender" : 0, "name" : "Flavio", "phoneNumber" : 123456 }"
dob: "1982-07-12"   gender: 0   name: "Flavio"   phoneNumber: 123456
"{ "age" : 20, "name" : "zhangshan" }"
***************************************************
"{ "encoding" : "UTF-8", "indent" : { "length" : 3, "use_space" : true }, "plug-ins" : [ "python", "c++", "ruby" ], "types" : [ { "A" : 1, "B" : 5 }, { "A" : 2, "B" : 6 } ] }"
***************************************************
json: QMap(("encoding", QVariant(QString, "UTF-8") ) ( "indent" ,  QVariant(QVariantMap, QMap(("length", QVariant(qulonglong, 3) ) ( "use_space" ,  QVariant(bool, true) ) )  ) ) ( "plug-ins" ,  QVariant(QVariantList, (QVariant(QString, "python") ,  QVariant(QString, "c++") ,  QVariant(QString, "ruby") )  ) ) ( "types" ,  QVariant(QVariantList, (QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 1) ) ( "B" ,  QVariant(qulonglong, 5) ) )  ) ,  QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 2) ) ( "B" ,  QVariant(qulonglong, 6) ) )  ) )  ) ) )
encoding: "UTF-8"
plugins:
        - "python"
        - "c++"
        - "ruby"
QVariant(QVariantList, (QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 1) ) ( "B" ,  QVariant(qulonglong, 5) ) )  ) ,  QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 2) ) ( "B" ,  QVariant(qulonglong, 6) ) )  ) )  )
type: QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 1) ) ( "B" ,  QVariant(qulonglong, 5) ) )  )
A: 1   B: 5
type: QVariant(QVariantMap, QMap(("A", QVariant(qulonglong, 2) ) ( "B" ,  QVariant(qulonglong, 6) ) )  )
A: 2   B: 6
length: 3
use_space: true

 

因爲比較簡單,這裏只做分享和記錄,不過多贅述。需要相關資源的,可以留言或者私我。下一篇,我們來記錄下jsoncpp的編譯和使用技巧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章