下面,举例;
首先,调用 json_loads() 函数,加载一个 json 数据,得到一个 json 对象;
然后,调用 json_object_get() 函数,获取对应的 json 对象;
此时,如果获取一个 json 数组对象,那么,可以有如下操作:
json_array_size() --- 获取 数组 容量;
json_array_get() --- 获取第 N 个数组元素,此时,数组元素是一个 json 对象;
那么,可以调用 json_object_get() 函数,获取相应的 json 对象。
或者,调用 json_string_value() 获取元素的 string 值;
//========================================================================
int iface_set_parse_conf(iface_set_t* pthis, char* pbuf)
{
json_t *result, *res, *item;
json_t obj;
int size, i;
const char p;
json_error_t error;
int iface_len;
json_t *ifaces, *wifi;
int j;
json_t *input = json_loads(pbuf, 0, &error);
if(NULL == input){
LOG("err\n");
return 1;
}
result = json_object_get(input, "result");
if(NULL == result){
LOG("get result err\n");
goto out;
}
res = json_object_get(result, "res");
if(NULL == res){
LOG("get res err\n");
goto out;
}
size = json_array_size(res);
if 0
log_debug("array size = %d\n", size);
endif
for(i = 0; i < size ; i++)
{
item = json_array_get(res, i);
obj = json_object_get(item, "band");
if(NULL == obj){
LOG("Not get band\n");
break;
}
p = json_string_value(obj);
LOG("get band = %s\n", p);
if(0 == memcmp(p, "2G", 2))
{
//2g
iface_set_get_device_2g(pthis, item);
ifaces = json_object_get(item, "ifaces");
if(NULL == ifaces)
continue;
iface_len = json_array_size(ifaces);
if(iface_len <= 0)
continue;
LOG("2G iface len = %d\n", iface_len);
for(j = 0; j < iface_len; j++)
{
wifi = json_array_get(ifaces, j);
obj = json_object_get(wifi, "guest");
if(NULL == obj){
continue;
}
if(1 == json_boolean_value(obj))
{
//guest
iface_set_get_wifi_2g_guest(pthis, wifi);
}
else
{
iface_set_get_wifi_2g(pthis, wifi);
}
}
}
if(0 == memcmp(p, "5G", 2))
{
//5g
iface_set_get_device_5g(pthis, item);
ifaces = json_object_get(item, "ifaces");
if(NULL == ifaces)
continue;
iface_len = json_array_size(ifaces);
if(iface_len <= 0)
continue;
LOG("5G iface len = %d\n", iface_len);
for(j = 0; j < iface_len; j++)
{
wifi = json_array_get(ifaces, j);
obj = json_object_get(wifi, "guest");
if(NULL == obj)
continue;
if(1 == json_boolean_value(obj))
{
//guest
iface_set_get_wifi_5g_guest(pthis, wifi);
}
else
{
iface_set_get_wifi_5g(pthis, wifi);
}
}
}
}//end for
out:
json_decref(input);
return 0;
}
韦凯峰Linux编程学堂,一瓶啤酒的价格,视频+文档,零基础入门,掌握Linux C/C++编程,Linux系统编程,用技术改变生活,改变自己,改变世界!