这是JSON文本:
{
"retcode": 0,
"result": {
"info": [{
"face": 180,
"flag": 8913472,
"nick": "tom",
"uin": 2951718842
}, {
"face": 252,
"flag": 512,
"nick": "jim",
"uin": 824317252
}, {
"face": 0,
"flag": 17302018,
"nick": "hanmeimei",
"uin": 1179162105
}, {
"face": 522,
"flag": 4719104,
"nick": "lilei",
"uin": 108219029
}]
}
}
下面是获取JSON文本“nick”节点的函数
char* getNickName()
{
char* path[20] = { "result", "info", "nick", (char *) 0 };
yajl_val v;
yajl_val node;
node = yajl_tree_parse(buffer, errbuf, sizeof(errbuf));
v = yajl_tree_get(node, path, yajl_t_string);
return YAJL_GET_STRING(v);
}
函数getNickName
应返回 lilei 或类似内容,但实际上它总是返回0.
因为不只有一个节点名为“nick”,所以yajl如何逐个解析“nick”?
如何获得 tom , jim 等值。
答案 0 :(得分:4)
首先需要获取 info 数组。然后遍历数组。
char* path[20] = { "result", "info", (char *) 0 };
yajl_val v;
yajl_val info;
info = yajl_tree_parse(buffer, errbuf, sizeof(errbuf));
if (info && YAJL_IS_ARRAY(info)) {
size_t len = info->u.array.len;
for(int i = 0;i < len; i++) {
const char *n_path[] = {"nick",(const char *)0};
yajl_val n = yajl_tree_get(f,n_path,yajl_t_string);
// here is what you need
char *nickname = YAJL_GET_STRING(n);
}
DONE