json qt 解析数组_Qt 解析JSon

本文介绍了如何使用QT标准库解析JSON对象,特别是处理数组的情况。通过包含QT脚本引擎,可以方便地读取PHP返回的JSON数据,并用C++进行处理。示例代码展示了如何获取并遍历JSON数组,打印出成员值。
摘要由CSDN通过智能技术生成

First time i find out this it took a while. But actually there is no

need any Additional code except QT itself, unless you want gain more

performance then QT standard library gives. So if you want to parse JSON

object first you have to include QT script engine.

#include

Let say PHP returns something like this.

echo json_encode(array('result' => array(1,2,3)));

So C++ code looks like:

QByteArray result;

result = QhttpClient->readAll();

QScriptValue sc;

QScriptEngine engine;

sc = engine.evaluate(QString(result)); // In new versions it may need to look like engine.evaluate("(" + QString(result) + ")");

if (sc.property("result").isArray())

{

QStringList items;

qScriptValueToSequence(sc.property("result"), items);

foreach (QString str, items) {

qDebug("value %s",str.toStdString().c_str());

}

}

In this example this code writes something like:

value 1

value 2

value 3

values comes from generated PHP script. Let say php now gives us back something like:

echo json_encode(array('error' => false));

In this case just more simple syntax.

if (sc.property("error").toBoolean() == true)

qDebug("Error detected");

else

qDebug("All ok");

And finally most complex example witch should be ready to use for any purpose. Let say PHP gives something like this:

echo json_encode(

array('result' =>

array

(

array('id' => '1' ,'date' => '487847','nick' => 'Remigiijus'),

array('id' => '1' ,'date' => '487847','nick' => 'remdex')

)

)

);

In this case we must include additional file:

#include

And let say we want to print nick names. So our C++ file will look like.

QByteArray result;

result = QhttpClient->readAll();

QScriptValue sc;

QScriptEngine engine;

sc = engine.evaluate(QString(result));// In new versions it may need to look like engine.evaluate("(" + QString(result) + ")");

if (sc.property("result").isArray())

{

QScriptValueIterator it(sc.property("result"));

while (it.hasNext()) {

it.next();

qDebug("Nick %s",it.value().property("nick").toString().toStdString().c_str());

}

}

In this case we just use QScriptValueIterator and iterate through array. Anyway from this point everything is possible :)

http://qtwiki.org/Parsing_JSON_with_QT_using_standard_QT_library

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值