Saturday, May 2, 2009

Qt4 JSON Stream Reader

JSON, short for JavaScript Object Notation, is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).

One way to use JSON with Qt4 is using the QScriptEngine (engine.Evaluate(jsonSource)), But I like Reinventing the wheel, so I've written a simple JSON Stream Reader that works "almost" like the QXmlStreamReader.

You've a readNext() method that read the next token and returns its type, and two properties name() and values() that Returns the name of the Property, Object or Array and the Value of the Property in a QVariant that can be Bool, Int, Double or String.

Below there's an Example of How to use the JSON Stream Reader. Maybe you can use it to create an automatic Object Mapper like the Xml Object Mapper that I've posted a couple of weeks ago.

QFile file("test.json");
if (! {
qDebug() << file.errorString();

THJsonStreamReader reader(&file);
while (!reader.atEnd()) {
switch (reader.readNext()) {
case THJsonStreamReader::PropertyNumerical:
qDebug() << " - Property Numerical" << << reader.value();
case THJsonStreamReader::PropertyString:
qDebug() << " - Property String" << << reader.value();
case THJsonStreamReader::PropertyFalse:
qDebug() << " - Property False" << << reader.value();
case THJsonStreamReader::PropertyTrue:
qDebug() << " - Property True" << << reader.value();
case THJsonStreamReader::PropertyNull:
qDebug() << " - Property Null" <<;
case THJsonStreamReader::Object:
qDebug() << "Object" <<;
case THJsonStreamReader::ObjectEnd:
qDebug() << "Object End";
case THJsonStreamReader::Array:
qDebug() << "Array" <<;
case THJsonStreamReader::ArrayEnd:
qDebug() << "Array End";


The Source Code is Available Here: Qt4 JSON Stream Reader Source Code.

No comments:

Post a Comment