在json中返回QtQSqlQuery
Qt QSqlQuery return in json
我在应用程序中创建了一个sqlquery方法,该方法基本上可以获得SQL命令并以json形式返回结果,问题是当填充"
和其他有问题的字符时,会创建无效的json。。
我试图先创建一个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();
}
小型设计说明。。我建议重新审查有关错误处理的设计。您从函数返回的QString可以是正确的JSON文档,也可以只是错误文本。因此,您实际上将不同的结果集类型混合在一种语言类型中——字符串。因此,您需要在代码中进行一些额外的检查,以了解实际发生了什么。
问题5.x样本:
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();
}
我建议使用适当的Json实现来正确地转义引号等。
如果您使用的是Qt5:Qt5附带了作为qtbase一部分捆绑的QJsonDocument。
如果您使用的是Qt4:没有内置Json支持,但您可以使用第三方库,如qjson。
如果你真的不能使用一个合适的lib,你可以自己做,并手动转义特殊字符(下面是一个列表)。
例如
QString escapeForJson(QString s) {
s = s.replace(QLatin1String("""), QLatin1String("\"));
…
return s;
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 在json中返回QtQSqlQuery