cJSON用法

来源:互联网 发布:商标域名注册条件 编辑:程序博客网 时间:2024/04/28 11:19
#include <stdio.h>
#include "cJSON.h"

char* makeJson(void)
{
    cJSON* pJsonRoot = NULL;

    pJsonRoot = cJSON_CreateObject();
    if(NULL == pJsonRoot)
    {
        printf("cJSON_CreateObject failed\n");
        return NULL;    
    }
    cJSON_AddStringToObject(pJsonRoot,"hello","hello world");
    cJSON_AddNumberToObject(pJsonRoot,"number",10000);
    cJSON_AddBoolToObject(pJsonRoot,"bool",1);

    cJSON* pSubJson = NULL;
    pSubJson = cJSON_CreateObject();
    if(NULL == pSubJson)
    {
        cJSON_Delete(pJsonRoot);    
        return NULL;
    }
    cJSON_AddStringToObject(pSubJson,"subjsonobj","a sub json string");
    cJSON_AddItemToObject(pJsonRoot,"subobj",pSubJson);

    char* p = cJSON_Print(pJsonRoot);
    if(NULL == p)
    {
        cJSON_Delete(pJsonRoot);    
        return NULL;
    }
    cJSON_Delete(pJsonRoot);

    return p;
}
void parseJson(char* pMsg)
{
    if(NULL == pMsg)
    {
        return;    
    }
    cJSON* pJson = cJSON_Parse(pMsg);
    if(NULL==pJson)
    {
        return ;    
    }
    cJSON* pSub = cJSON_GetObjectItem(pJson,"hello");
    if(NULL == pSub)
    {
        printf("GetObjectItem hello failed\n");    
        return ;
    }
    printf("obj_1: %s\n",pSub->valuestring);

    pSub = cJSON_GetObjectItem(pJson,"number");
    if(NULL == pSub)
    {
        printf("cJSON_GetObjectItem number failed\n");    
        return ;
    }
    printf("obj_2: %d\n",pSub->valueint);

    pSub = cJSON_GetObjectItem(pJson,"bool");
    if(NULL == pSub)
    {
        printf("cJSON_GetObjectItem bool failed\n");    
        return ;
    }
    printf("obj_3: %d\n",pSub->valueint);

    pSub = cJSON_GetObjectItem(pJson,"subobj");
    if(NULL == pSub)
    {
        printf("cJSON_GetObjectItem subobj failed\n");    
        return ;
    }
    cJSON* pSubSub = cJSON_GetObjectItem(pSub,"subjsonobj");
    if(NULL == pSubSub)
    {
        printf("cJSON_GetObjectItem subjsonobj failed\n");    
        return ;
    }
    printf("sub_obj_1: %s\n",pSubSub->valuestring);


    cJSON_Delete(pJson);
}
int main(void)
{
    char* p = makeJson();
    if(NULL == p)
    {
        printf("create json failed\n");
        return -1;    
    }
    printf("%s\n",p);

    parseJson(p);
    return 0;

}


输出效果:

gcc -o parsejson parsejson.c cJSON.c cJSON.h -Wall -lm
ljc@ljc:~/test/json/cJSON$ sudo ./parsejson
{
    "hello":    "hello world",
    "number":    10000,
    "bool":    true,
    "subobj":    {
        "subjsonobj":    "a sub json string"
    }
}
obj_1: hello world
obj_2: 10000
obj_3: 1
sub_obj_1: a sub json string

0 0
原创粉丝点击