Qt QSqlQuery return in json

Solution 1:

Small design note.. I would advise to review design regarding error handling. You are returning QString from your function which can be either proper JSON document or just error text. So, you actually mixing different result set types within one language type - String. So you need to make some extra checks in the code around to understand what's actually happened.

Qt 5.x sample:

QString Api::SQLQuery(const QString & sqlquery) {
  QSqlQuery query;

  query.setForwardOnly(true);
  if (!query.exec(sqlquery))
      return QString();

  QJsonDocument  json;
  QJsonArray     recordsArray;

  while(query.next()) {
     for(int x=0; x < query.record().count(); x++) {
         QJsonObject        recordObject;

     recordObject.insert( query.record().fieldName(x), 
               QJsonValue::fromVariant(query.value(x)) );   
     }
     recordsArray.push_back(recordObject);
  }
  json.setArray(recordsArray);

  return json.toJson();

}

Solution 2:

I'd suggest to use a proper Json implementation to get the escaping of quotes etc. right.

If you're using Qt5: Qt5 comes with QJsonDocument bundled as part of qtbase.

If you're using Qt4: There's no Json support built-in, but you can use third-party libraries such as qjson.

If you really really can't use a proper lib, you can do it yourself and escape the special characters manually (Here's a list).

E.g.

QString escapeForJson(QString s) {
    s = s.replace(QLatin1String("\""), QLatin1String("\\\"));
    …
    return s;
}