cJson的用法(一) -C语言解析/生成 json数据

来源:互联网 发布:淘宝快递投诉怎么撤销 编辑:程序博客网 时间:2024/05/16 09:29

cJson这个库开源 跨平台,用来解析和生成json数据很方便。项目地址:https://github.com/DaveGamble/cJSON

只需要把cJson.c,cJson.h拷进项目就ok.


下面直接上代码:

#include<stdio.h>#include<stdlib.h>#include"cJSON.h"int main(){/*************    json的解析***************************/char data[] = "{\"name\":\"邱于涵\",\"age\":20}";//json是json对象指针,json_name是 name对象的指针,json_age是age对象的指针cJSON *json=0, *json_name=0, *json_age=0;//解析数据包json = cJSON_Parse(data);//如果解析失败if (!json){printf("Error Before:", cJSON_GetErrorPtr());}else {json_age = cJSON_GetObjectItem(json, "age");//如果类型是 数字if(json_age->type==cJSON_Number){printf("年龄:%d\n", json_age->valueint);}json_name = cJSON_GetObjectItem(json, "name");//如果类型是 字符串if (json_name->type == cJSON_String){printf("姓名:%s\n", json_name->valuestring);}//释放内存cJSON_Delete(json);}     /**************************     json的生成 **********************************/cJSON * jsonroot=0;char * jsonout=0;//创建根节点对象jsonroot = cJSON_CreateObject();//向根节点加入数字对象cJSON_AddNumberToObject(jsonroot, "age", 19);//向根节点加入字符串对象cJSON_AddStringToObject(jsonroot, "name", "山楂");//解析成字符串jsonout=cJSON_Print(jsonroot);printf("%s", jsonout);//释放json对象的空间cJSON_Delete(jsonroot);//释放jsonout的空间free(jsonout);system("pause");return 0;}
运行结果:



阅读全文
0 0
原创粉丝点击