Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1800595
  • 博文数量: 306
  • 博客积分: 3133
  • 博客等级: 中校
  • 技术积分: 3932
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-19 16:50
文章分类

全部博文(306)

文章存档

2018年(7)

2017年(18)

2016年(39)

2015年(35)

2014年(52)

2013年(39)

2012年(22)

2011年(29)

2010年(53)

2009年(12)

分类: LINUX

2011-03-04 15:02:34

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.

 
json_encode(('result' => (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:

 
json_encode(('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:

 
json_encode(
('result' =>

(
('id' => '1' ,'date' => '487847','nick' => 'Remigiijus'),
('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 :)



阅读(9680) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

chinaunix网友2011-03-27 13:52:06

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com