Home

Awesome

Qt Json Autogen

A build-time tool that automatically generate implementation for C++ class serialization/deserialization to/from json.

If your project is based on Qt, this tool may help a lot.

Introduction

qasc(Qt Auto Serialization Compiler) is a code generator based on moc in Qt 5.15.2 source, it will generate the implementation of conversions between classes/enumerations and QJsonObject/QString.

In order to have as little association with the QObject framework as possible, qasc implements the conversion between enumeration and string itself.

Enumeration

// Source
enum Direction {
    __qas_attr__("west")
    West,

    East,

    North,
    __qas_exclude__
    South,
}

QAS_JSON_NS(Direction)

int main() {
    qDebug() << qAsEnumToJson(Direction::West);
    qDebug() << qAsEnumToJson(Direction::East);
    qDebug() << qAsEnumToJson(Direction::North);
    qDebug() << qAsEnumToJson(Direction::South);
    return 0;
}
# Output
"west"
"East"
"North"
""

Class/Struct

// Source
class Class {
public:
    class Student {
    public:
        enum Gender {
            Male,
            Female,
        };
        QAS_JSON(Gender);

        QString name;
        Gender gender;
        int age;
    };
    QAS_JSON(Student);

    __qas_attr__("Class")
    QString className;

    QMap<QString, Student> students; // id -> student

    __qas_exclude__
    QString otherInfo;
};
QAS_JSON_NS(Class)

int main() {
    Class cls;
    cls.className = "F114514";
    cls.students = {
        {"1", {"alice", Class::Student::Female, 18}},
        {"2", {"bob",   Class::Student::Male,   17}},
        {"3", {"mark",  Class::Student::Male,   19}},
    };
    cls.otherInfo = "PHP is the best programming language.";
    qDebug().noquote() << QJsonDocument(qAsClassToJson(cls)).toJson();
    return 0;
}
# Output
{
    "Class": "F114514",
    "students": {
        "1": {
            "age": 18,
            "gender": "Female",
            "name": "alice"
        },
        "2": {
            "age": 17,
            "gender": "Male",
            "name": "bob"
        },
        "3": {
            "age": 19,
            "gender": "Male",
            "name": "mark"
        }
    }
}

Supported Types

C++ TypeJSON Type
custom structures/classesobject
booltrue/false
signed and unsigned integral typesnumber
float and doublenumber
enum and enum classstring
QStringstring
iteratable lists (QVector, QList, std::vector, std::list)array
sets (QSet, std::set, std::unordered_set)array
map (QMap, QHash, std::map, std::unordered_map)object

How To Use

Add Into CMake Project

Details

CMake Identifiers Intro

qas_wrap_cpp

qas_wrap_cpp(<VAR> src_file1 [src_file2 ...]
            [TARGET target]
            [OPTIONS ...]
            [DEPENDS ...])

QASC Tool

Acknowledgements

License