有时应用程序需要加载数据库中有用数据,目前交主流的就是动态语言创建JSON数据格式,然后应用程序可以解析。
1、在pro文件中添加script,如右: QT += script
2、需要添加头文件#include<QtScript>
1、在pro文件中添加script,如右: QT += script
2、需要添加头文件#include<QtScript>
3、代码如下,代码str1为json数组,str2为json单个对象的字符串。
#include "json.h"
#include <QApplication>
#include <QtScript>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Json w;
w.show();
QString str1 = "[{\"user\":\"hwb\"},{\"user\":\"zbh\"},{\"user\":\"zf\"}]";
QString str2 = "{\"age\":\"26\"}";
QScriptEngine engine;
QScriptValue sc = engine.evaluate("value=" + str1);
if(sc.isArray()) //解析数组
{
QScriptValueIterator it(sc);
while (it.hasNext())
{
it.next();
if(!it.value().property("user").toString().isEmpty())
{
qDebug()<<it.value().property("user").toString();
}
}
}
sc = engine.evaluate("value=" + str2);
QScriptValueIterator it(sc); //解析json数据
if (it.hasNext())
{
it.next();
qDebug()<<it.name()<<":"<<it.value().toString();
}
return a.exec();
}