cJSON库使用

cJSON安装


在Linux下,使用下面命令下载源码
git clone https://github.com/DaveGamble/cJSON.git

进入cJSON目录,执行make && make install 进行编译安装。

cJSON使用


下面使用一个简单的例子对其使用方式进行说明

  1 #include 
  2 #include 
  3 
  4 int main()
  5 {
  6     char * ptr = "{\"firstName\":\"Brett\"}";
  7 
  8     cJSON *cj = cJSON_Parse(ptr);
  9     if( !cj     )
 10     {
 11         printf("cjson_parse failed \n");
 12         return -1 ;
 13     }
 14 
 15     cJSON *item = cJSON_GetObjectItem(cj,"firstName");
 16     if( item)
 17     {
 18         printf("%s \n",item->valuestring);
 19     }
 20 
 21     cJSON_Delete(cj);
 22 
 23 }         

编译:
gcc test.c -lcjson -o test
主要过程分为三步:

  • 使用cJSON_Parse将字符串转换为cJSON结构。
  • 使用cJSON_GetObjectItem获取指定键对应的值。
  • 使用cJSON_Delete销毁创建的cJSON结构。

你可能感兴趣的:(cJSON库使用)