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()); }
结果如图: