cJSON使用

#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:%s\n",json_data->valuestring);
        }

        user_id = cJSON_GetObjectItem( json , "id");
        if( user_id->type == cJSON_String )
        {   
      printf("id:%s\n",user_id->valuestring);
        }

    user = cJSON_GetObjectItem( json , "user");
        if( user->type == cJSON_String )
        {
            printf("user:%s\r\n",user->valuestring);
        }

    mac = cJSON_GetObjectItem( json , "mac");
        if( mac->type == cJSON_String )
        {
            printf("mac:%s\r\n",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("%s\n",out);

    cJSON_Delete(root); 
    return out;
}

int main(){
    char *test = Create_cjson();
    printf("generate json:%s\nParse json:\n",test);
    Parse_json(test);

}

cJSON_Print函数打印的
cJSON_PrintUnformatted打印的

对比两个打印的函数:

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掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值