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 (!file.open(QIODevice::ReadOnly)) {
qDebug() << file.errorString();
return(1);
}

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

file.close();



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

No comments:

Post a Comment