📜 ⬆️ ⬇️

QJson as a library for working with JSON in Qt


Hi, Habr!

On Habré have not yet written about QJson - a great and very simple tool for working with JSON on Qt. In general, Qt recommends using XML - but it seems to me that in very many cases it is too redundant or redundant. In some cases it is better to use JSON. In this post I will tell you how to download, build and use QJson to work with JSON in Qt.

Attention! This post is a note. All that you read here can be found in Google and on the off-site project - but I think that such a note would not be superfluous.

')

Getting


QJson - 3rd party, in order to work with it, you must first get and collect it. This can be done in two ways - from the official website of the project or with gitorious . We swing, we unpack and we pass to the following stage.

Installation


QJson developers recommend building via cmake.

Windows


set PATH=%PATH%;C:\path_to_cmake_\bin cd path_where_i_unpacked_qjson cd build cmake -G "MinGW Makefiles" .. mingw32-make mingw32-make install 


Linux / Mac


 cd where_i_downloaded_qjson mkdir build cd build cmake .. make sudo make install 


Getting started


QJson allows you to work with JSON based on QVariant (QVariantMap, QVariantList) which gives it flexibility. He can parse, write JSON and implement QObjects.

First of all, let's add a line to the .pro file:
 LIBS += -lqjson 


Now our project depends on qjson and is able to work with it.

Parsim QJson


 #include<qjson/parser.h> QVariant parseJSON(const QString &json) { QJson::Parser parser; //   json' bool ok; // false    return parser.parse (json, &ok); // QVariant } 


May we parse this JSON:
 { "encoding" : "UTF-8", "plug-ins" : [ "python", "c++", "ruby" ], "indent" : { "length" : 3, "use_space" : true } } 


Here is this code:
 QJson::Parser parser; bool ok; QVariantMap result = parser.parse (json, &ok).toMap(); if (!ok) { qFatal("    - -."); exit (1); } qDebug() << "encoding:" << result["encoding"].toString(); qDebug() << "plugins:"; foreach (QVariant plugin, result["plug-ins"].toList()) { qDebug() << "\t-" << plugin.toString(); } QVariantMap nestedMap = result["indent"].toMap(); qDebug() << "length:" << nestedMap["length"].toInt(); qDebug() << "use_space:" << nestedMap["use_space"].toBool(); 


The output to the debug console will be:
 encoding: "UTF-8" plugins: - "python" - "c++" - "ruby" length: 3 use_space: true 


Writing from QVariant to JSON


I will only leave this example here:
 QVariantList people; QVariantMap bob; bob.insert("Name", "Bob"); bob.insert("Phonenumber", 123); QVariantMap alice; alice.insert("Name", "Alice"); alice.insert("Phonenumber", 321); people << bob << alice; QJson::Serializer serializer; QByteArray json = serializer.serialize(people); qDebug() << json; 


The output in the debug console will be:
 "[ { "Name" : "Bob", "Phonenumber" : 123 }, { "Name" : "Alice", "Phonenumber" : 321 } ]" 


Great, isn't it?

QObject Serialization


It is also possible to serialize a QObject instance into JSON. All class attributes are defined as properties and will be ordered. Suppose the class definition looks like this:
 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); private: QString m_name; int m_phoneNumber; Gender m_gender; QDate m_dob; }; 


This code will turn the Person object into JSON:
 Person person; person.setName("Flavio"); person.setPhoneNumber(123456); person.setGender(Person::Male); person.setDob(QDate(1982, 7, 12)); QVariantMap variant = QObjectHelper::qobject2qvariant(&person); Serializer serializer; qDebug() << serializer.serialize( variant); 


The console will display the following output:
 { "dob" : "1982-07-12", "gender" : 0, "name" : "Flavio", "phoneNumber" : 123456 } 


It is also possible to parse JSON in QObject. Imagine that the above JSON is in some kind of QString.
 Parser parser; QVariant variant = parser.parse(json); // json -  JSON  QString Person person; QObjectHelper::qvariant2qobject(variant.toMap(), &person); //   person   json 


Full API


Excellent described in English here .

My comment


Who can it be useful? Yes, anyone! Any developer who needs to store information in a light or user-friendly format.

Thanks for attention.

Source: https://habr.com/ru/post/147952/


All Articles