C语言库cJSON的使用例子
1、下载库
2、工程添加库
3、添加测试代码
#include <stdlib.h>
#include <stdio.h>
#include "cJSON.h"
char *createJson()
{
cJSON *pJsonMain = NULL;
pJsonMain = cJSON_CreateObject();
if (NULL == pJsonMain) { return NULL;}
cJSON_AddStringToObject(pJsonMain, "username", "QpfT21aU");
cJSON_AddStringToObject(pJsonMain, "password", "8J4sg@lw");
cJSON *pJsonSub = NULL;
pJsonSub = cJSON_CreateObject();
if (NULL == pJsonSub)
{
cJSON_Delete(pJsonMain);
return NULL;
}
cJSON_AddStringToObject(pJsonSub, "Level", "Just test");
cJSON_AddItemToObject(pJsonMain, "data", pJsonSub);
char *pJson = cJSON_PrintUnformatted(pJsonMain);
if (NULL == pJson)
{
cJSON_Delete(pJsonMain);
return NULL;
}
cJSON_Delete(pJsonMain);
return pJson;
}
void parseJson(char *pJsondata)
{
if (pJsondata == NULL)
{
return;
}
cJSON * pJson = cJSON_Parse(pJsondata);
if (NULL == pJson)
{
return;
}
cJSON *pSub_username = cJSON_GetObjectItem(pJson, "username");
if (NULL == pSub_username)
{
//get username from json failed;
}
printf("%s: %s\n", pSub_username->string, pSub_username->valuestring);
cJSON *pSub_password = cJSON_GetObjectItem(pJson, "password");
if (NULL == pSub_password)
{
//get username from json failed;
}
printf("%s: %s\n", pSub_password->string, pSub_password->valuestring);
cJSON *pSub = cJSON_GetObjectItem(pJson, "data");
if (NULL == pSub)
{
//get sub object failed
}
cJSON *pSubSub = cJSON_GetObjectItem(pSub, "Level");
if (NULL == pSubSub)
{
//get object from subject object failed;
}
printf("%s: %s\n", pSubSub->string, pSubSub->valuestring);
cJSON_Delete(pJson);
}
int main(void)
{
char *pJson = NULL;
pJson = createJson();
if (pJson == NULL) { return 0; }
printf("%s\n", pJson);
parseJson(pJson);
free(pJson);
return 0;
}
4、编译查看结果,本人用VS2017结果会报错,如下
该错误有两种修改方式
1)按错误提示修改库代码,不推荐该方法;
2)按照提示,给工程添加对应的宏即可,如下
编译结果如下
评论