1、构造json对象;2、向对象中添加元素;3、获取对象中元素;4、获取元素的值;5、json对象与数组互转;6、释放json对象空间; 
 
从官网直接下载cJSON源文件,添加到工程中即可。 
 
char jssd_def[256]; 
 
1、构造json对象; 
 
cJSON* root = NULL; 
 
cJSON* item = NULL; 
 
item = cJSON_CreateObject(); 
 
root = cJSON_CreateObject(); 
 
2、向对象中添加元素; 
 
        1、将对象作为元素进行添加: 
 
cJSON_AddItemToObject(item, "name", cJSON_CreateString("xiaopeng")); 
 
cJSON_AddItemToObject(item,"age",cJSON_CreateNumber(21)); 
 
cJSON_AddItemToObject(root,"root",item); 
 
        2、直接添加元素: 
 
        cJSON_AddItemToObject(root,"ID",cJSON_CreateNumber(1)); 
 
3、获取对象中元素; 
 
root = cJSON_Parse(jssd_def); 
item = cJSON_GetObjectItem(root, "root"); 
 
4、获取元素的值; 
 
cJSON* age = NULL; 
 
age = cJSON_GetObjectItem(item, "age"); 
 
printf( "age=%d\r\n", age->valueint ); 
 
5、json对象与数组互转; 
 
        1、json对象转字符串 
 
sprintf(jssd_def, "%s", cJSON_Print(root));//带格式化\n\t 
 
sprintf(jssd_def, "%s", cJSON_PrintUnformatted(root));//不带格式 
 
        2、字符串转json对象 
 
root = cJSON_Parse(jssd_def); 
 
6、释放json对象空间; 
 
 如果使用cJSON_Delete(cJSON *c);进行对象释放:当一个对象是另一个对象的元素时,只调用外层对象释放,否则会出现硬件错误;如果内层对象被释放,再释放外层对象,也会出现硬件错误。如果不放心,则可以直接使用free进行多次释放。 
 
 //cJSON_Delete( root );等价于{free( item );free( root );} 
 //警告:使用cJSON_Delete( root );则不能使用cJSON_Delete( item ); 
 cJSON_Delete( root ); 
 
 
 |   
     
  
 |