cJSON使用
发布时间:2020-12-16 19:46:58 所属栏目:百科 来源:网络整理
导读:#include "cJSON.h" #include stdio.h #include stdlib.h int Parse_json( char *srcJson ){ cJSON *json , *json_data , *data , *user_id , *user , *mac , *raw ; json = cJSON_Parse(srcJson); if (!json){ printf ( "Error before: [ %s ]n" ,cJSON_Ge
#include "cJSON.h"
#include <stdio.h>
#include <stdlib.h>
int Parse_json( char *srcJson )
{
cJSON *json,*json_data,*data,*user_id,*user,*mac,*raw;
json = cJSON_Parse(srcJson);
if (!json){
printf("Error before: [%s]n",cJSON_GetErrorPtr());
}else{
data = cJSON_GetObjectItem( json,"data");
json_data = cJSON_GetObjectItem(data,"raw");
if( json_data->type == cJSON_String )
{
printf("raw:%sn",json_data->valuestring);
}
user_id = cJSON_GetObjectItem( json,"id");
if( user_id->type == cJSON_String )
{
printf("id:%sn",user_id->valuestring);
}
user = cJSON_GetObjectItem( json,"user");
if( user->type == cJSON_String )
{
printf("user:%srn",user->valuestring);
}
mac = cJSON_GetObjectItem( json,"mac");
if( mac->type == cJSON_String )
{
printf("mac:%srn",mac->valuestring);
}
cJSON_Delete(json);
}
return 0;
}
char *Create_cjson(void){
cJSON *data,*root;
root=cJSON_CreateObject();
data = cJSON_CreateObject();
cJSON_AddItemToObject(root,"data",data);
cJSON_AddStringToObject(data,"raw","AAAAAxBBBBBBBxccccccccccc");
cJSON_AddStringToObject(root,"id","01234567");
cJSON_AddStringToObject(root,"user","admin");
cJSON_AddStringToObject(root,"mac","01234567891");
char *out = cJSON_Print(root);
// char *out = cJSON_PrintUnformatted(root);
// printf("%sn",out);
cJSON_Delete(root);
return out;
}
int main(){
char *test = Create_cjson();
printf("generate json:%snParse json:n",test);
Parse_json(test);
}
对比两个打印的函数: CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
{
return (char*)print(item,true,&global_hooks);
}
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
{
return (char*)print(item,false,&global_hooks);
}
static unsigned char *print(const cJSON * const item,cJSON_bool format,const internal_hooks * const hooks)
{
printbuffer buffer[1];
unsigned char *printed = NULL;
memset(buffer,0,sizeof(buffer));
/* create buffer */
buffer->buffer = (unsigned char*) hooks->allocate(256);
buffer->format = format;
buffer->hooks = *hooks;
....
可以看到buffer在此分配了内存空间,所以在输出后要记得free掉。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |