微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/json/288616.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐