{ "datastreams": [ { "id": "tempture","datapoints": [ { "at": "2017-02-04T20:33:45","value": 19 } ] } ] }
如何用cJSON解析上述的json格式的字符串;
首先分析下:
根节点下有一个键是datastreams,值是一个数组;
数组里面有2条记录,第一条是一个键值对,第二条当然也是键值对,
但是这个键值对的值是嵌套的,即值也是由两个键值对组成的;
//1. 首先创建一个根节点,即一个空的大括号 {} root=cJSON_CreateObject(); //2.添加一个键值对,键是datastrems,值是个数组,用cJSON_CreateArray来创建 cJSON_AddItemToObject(root,"datastreams",subdir=cJSON_CreateArray()); //3.这个数组里面又是一个对象,所以用cJSON_CreateObject来创建 cJSON_AddItemToObject(subdir,"dira",dir1=cJSON_CreateObject()); //4.往新创建的对象里添加键值对 "id","tempture" cJSON_AddStringToObject(dir1,"id","tempture"); //5.再添加一个键值对,键是datapoints 对是一个数组,用cJSON_CreateArray来创建 cJSON_AddItemToObject(dir1,"datapoints",subdir2=cJSON_CreateArray()); //再次嵌套一个数组 //6.数组里是一个对象用cJSON_CreateObject来创建,里面有两个键值对 cJSON_AddItemToObject(subdir2,"dirb",dir2=cJSON_CreateObject()); //7.添加两个键值对 cJSON_AddStringToObject(dir2,"at","2017-02-04T20:33:45"); cJSON_AddNumberToObject(dir2,"value",19); out=cJSON_Print(root); cJSON_Delete(root); printf("%s\n",out); myfree(out);
再来看一个例子:
[ {name:"中国",province:[ { name:"黑龙江",cities:{ city:["哈尔滨","大庆"] }}]},{name:"广东",cities:{ city:["广州","深圳","珠海"] } } ]
cJSON *root,*dir1,*dir2,*dir3,*dir4,*dir5; root=cJSON_CreateArray(); cJSON_AddItemToObject(root,"root1",dir1=cJSON_CreateObject());//发现里面第一个就是{}套着,那就将该{}里的内容都填写好 //分析下,这里第一个元素是字符串键值对 cJSON_AddStringToObject(dir1,"name","中国"); //第二个元素键是province,值是个数组 cJSON_AddItemToObject(dir1,"province",dir2=cJSON_CreateArray()); //数组里又是一个对象,里面有两个键值对 cJSON_AddItemToObject(dir2,"dir3",dir3=cJSON_CreateObject()); cJSON_AddStringToObject(dir3,"黑龙江"); cJSON_AddItemToObject(dir3,"cities",dir4=cJSON_CreateObject()); //对象里是一个键值对 //键是city,值是一个数组 cJSON_AddItemToObject(dir4,"city",dir5=cJSON_CreateArray()); cJSON_AddStringToObject(dir5,"xxx","哈尔滨"); cJSON_AddStringToObject(dir5,"大庆"); //------------------------------------------------------- cJSON_AddItemToObject(root,"root2",dir1=cJSON_CreateObject()); cJSON_AddStringToObject(dir1,"广东"); cJSON_AddItemToObject(dir1,dir2=cJSON_CreateObject()); cJSON_AddItemToObject(dir2,dir3=cJSON_CreateArray()); cJSON_AddStringToObject(dir3,"广州"); cJSON_AddStringToObject(dir3,"深圳"); cJSON_AddStringToObject(dir3,"珠海"); out=cJSON_Print(root); cJSON_Delete(root); buf_length=sprintf(buf,"%s",out); printf("%s\n",out); myfree(out);