C语言中对json格式数据的解析和封装
首先需要调库:#include <cJSON.h>
Json的数据结构介绍:
/* The cJSON structure: */
typedef struct cJSON
{
/*next/prev允许您遍历数组/对象链。或者,使用GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* 数组或对象项将有一个子指针指向数组/对象中的项链。 */
struct cJSON *child;/* 项目的类型,如上所述。*/
int type;/* 字符串, if type==cJSON_String */
char *valuestring;
/* 数值, if type==cJSON_Number */
int valueint;
/* 小数数据, if type==cJSON_Number */
double valuedouble;/* 项的名称字符串,如果此项是的子项,或在对象的子项列表中。*/
char *string;
} cJSON;
Json格式文本解析:
#define TEST2 "{\n\"auth\": \"auc_d0dd49997dd17b12f76b74fe51d0de3fd772718b\",\n\"sessionId\": \"5129110798518519880764729435382\"\n}"
char* buffer = TEST2;
cJSON* json = cJSON_Parse(buffer);
cJSON* name = cJSON_GetObjectItem(json, "name");
cJSON* num = cJSON_GetObjectItem(json, "num");
printf("%s,%s",name->valuestring,num->valueint);
Json格式文本封装:将多条字符串合成一条json格式数据
const char* client_id = "12345678";
const char* sessionid = "abcdefg";
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "authCode", client_id);
cJSON_AddStringToObject(root, "sessionId", sessionid);//这里的添加处理字符串以外还可以添加很多类型的数据
char *auth_resp_info = cJSON_Print(root);
printf("%s,%s",auth_resp_info);