【发布时间】:2013-08-06 04:56:21
【问题描述】:
我在我的应用程序中创建了一个 sqlquery 方法,它基本上获取一个 SQL 命令并以 json 格式返回结果,问题是当填充 " 和其他有问题的字符时,这会创建错误的 jsons..
我尝试先创建一个QObject,然后将其序列化为JSON,但无法实现。
即使数据包含“符号”,如何使该方法生成有效的json?
QString Api::SQLQuery(const QString & sqlquery)
{
QSqlQuery query;
bool firstline = true;
query.setForwardOnly(true);
if(query.exec(sqlquery))
{
QString answer = "[";
while(query.next())
{
if(firstline){firstline = false;}else {answer += ",";}
answer += "{";
for(int x=0; x < query.record().count(); ++x)
{
if(x != 0){answer += ",";}
answer += "\""+query.record().fieldName(x) +"\":\""+ query.value(x).toString()+"\"";
}
answer += "}";
}
answer += "]";
return answer;
}
else
{
return query.lastError().text() ;
}
}
解决方案:
感谢答案,这是正确的方法:
QString Api::SQLQuery(const QString & sqlquery) {
QSqlQuery query;
query.setForwardOnly(true);
if (!query.exec(sqlquery))return QString();
QJsonDocument json;
QJsonArray recordsArray;
while(query.next())
{
QJsonObject recordObject;
for(int x=0; x < query.record().count(); x++)
{
recordObject.insert( query.record().fieldName(x),QJsonValue::fromVariant(query.value(x)) );
}
recordsArray.push_back(recordObject);
}
json.setArray(recordsArray);
return json.toJson();
}
【问题讨论】:
标签: c++ mysql json qt qsqlquery