cJSON使用

前端之家收集整理的这篇文章主要介绍了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_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掉。

原文链接:https://www.f2er.com/json/288616.html

猜你在找的Json相关文章