Flavio Castelli

Debugging my life.

QJson: A Qt-based Library for Mapping JSON Data to QVariant Objects

| Comments

In order to realize a project of mine I started looking for a Qt library for mapping JSON data to Qt objects.

I came over a couple of solutions but none of them made me happy. So in the last weekend I wrote my own library : QJson The library is based on Qt toolkit and converts JSON data to QVariant instances. JSON arrays will be mapped to QVariantList instances, while JSON’s objects will be mapped to QVariantMap. The JSON parser is generated with Bison, while the scanner has been coded by me.

Usage

Converting JSON’s data to QVariant instance is really simple:

[] [ ]
1
2
3
4
5
// create a JSonDriver instance
JSonDriver driver;
bool ok;
// json is a QString containing the data to convert
QVariant result = driver.parse (json, &ok);

Suppose you’re going to convert this JSON data:

[JSON data] [ ]
1
2
{ "encoding" : "UTF-8", "plug-ins" : [ "python", "c++", "ruby" ],
  "indent" : { "length" : 3, "use_space" : true } }

The following code would convert the JSON data and parse it:

[] [ ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
JSonDriver driver;
bool ok;
QVariantMap result = driver.parse (json, &ok).toMap();
if (!ok) {
  qFatal("An error occured during parsing");
  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 would be:

encoding: "UTF-8" plugins: - "python" - "c++" - "ruby" length: 3 use_space: true

Requirements

QJson requires:

  • cmake
  • Qt

Obtain the source

Actually QJson code is hosted on KDE subversion repository. You can download it using a svn client:

svn co svn://anonsvn.kde.org/home/kde/trunk/playground/libs/qjson

For more informations visit QJson site

Comments