QT5开发环境集成了解析JSON表达式的库。使用很方便。
友情提示一下,好像在QT4环境里。须要到官网下载相关的库文件才干使用解析功能。话不多说,上代码
1、在pro文件里增加
QT += script
2、增加头文件
#include <QtScript/QScriptEngine>
3、在须要解析的地方增加例如以下代码:
比如须要解析的JSON表达式为:
解析代码为:
void MainWindow::replyFinished(QNetworkReply * reply)
{
QByteArray data = reply->readAll();
QString str(data);
QMessageBox::information(this, "reslut", str);
QScriptEngine engine;
QScriptValue sc = engine.evaluate("value=" + str);
if(sc.property("errorCode").toString()!= "0")
{
QMessageBox::information(this, "错误", "查询出现错误,请又一次查询!");
return ;
}
//外层JSOM表达式,翻译结果
this->ui->outEdit->setText(sc.property("translation").toString());
//第二层JSON表达式。网络延伸
QScriptValue subsc = sc.property("web");
QScriptValue subsc1 = subsc.property(0);
QScriptValue subsc2 = subsc.property(1);
QScriptValue subsc3 = subsc.property(2);
this->ui->extendEdit->setText(subsc1.property("key").toString()+":");
this->ui->extendEdit->append(subsc1.property("value").toString());
this->ui->extendEdit->append(subsc2.property("key").toString()+":");
this->ui->extendEdit->append(subsc2.property("value").toString());
this->ui->extendEdit->append(subsc3.property("key").toString()+":");
this->ui->extendEdit->append(subsc3.property("value").toString());
}
结果如图: