项目中要在处理能力不强的下位机中发送和解析JSON格式的报文,没发现在这个优秀的cJSON开源库之前还想着自己写个简单的,如果让我自己写那肯定一堆问题,初次使用是在vs中没配合下位机使用的,感觉还挺好用的。
用的话把.c、.h文件移植到你的工程里边就行。
发送和解析的JSON都长这样:
组装这个JSON:
//先组装一个JSON
char *creatJson()
{
//header
cJSON *header = cJSON_CreateObject();
int code = 101;
char *id = "7cdfa13f2f7e";
int dev_type=1;
char *crc="ffff";
//body
cJSON *body = cJSON_CreateObject();
int status=1;
int bri=100;
//创建JSON对象
cJSON *code101 = cJSON_CreateObject();
//把header加到code101中,并向header中添加子条目
cJSON_AddItemToObject(code101, "header", header);
if (cJSON_AddNumberToObject(header, "code", code) == NULL)
{
printf("cJSON_AddNumberToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
if (cJSON_AddStringToObject(header, "id", "asdfghvcdfsd") == NULL)
{
printf("cJSON_AddStringToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
if (cJSON_AddNumberToObject(header, "dev_type", dev_type) == NULL)
{
printf("cJSON_AddNumberToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
if (cJSON_AddStringToObject(header, "crc", "ffff") == NULL)
{
printf("cJSON_AddStringToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
//把body加到code101中,并向body中添加子条目
cJSON_AddItemToObject(code101, "body", body);
if (cJSON_AddNumberToObject(body, "status", 1) == NULL)
{
printf("cJSON_AddNumberToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
if (cJSON_AddNumberToObject(body, "bri", 100) == NULL)
{
printf("cJSON_AddNumberToObject failed\n");
cJSON_Delete(header);
cJSON_Delete(code101);
return NULL;
}
//把JSON格式的报文格式化为字符串
char *s = cJSON_Print(code101);
cJSON_Delete(code101);
return s;
}
解析这个JSON:
//把解析到的值打印出来
void parse_JSON(char *s)
{
//header
int code;
char *id = NULL;
int dev_type ;
char *crc;
//body
int status;
int bri;
cJSON *header = NULL;
cJSON *body = NULL;
//从字符串s中获取cJSON对象
cJSON *codex = cJSON_Parse(s);
//header
header = cJSON_GetObjectItem(codex, "header");
cJSON *t = cJSON_GetObjectItem(header, "code");
code = t->valueint;
printf("code: %d\n", code);
t = cJSON_GetObjectItem(header, "id");
id = t->valuestring;
printf("id:%s\n", id);
t = cJSON_GetObjectItem(header, "dev_type");
dev_type = t->valueint;
printf("dev_type:%d\n", dev_type);
t = cJSON_GetObjectItem(header, "crc");
crc = t->valuestring;
printf("crc:%s\n", crc);
//body
body = cJSON_GetObjectItem(codex, "body");
t = cJSON_GetObjectItem(body, "status");
status = t->valueint;
printf("status:%d\n", status);
t = cJSON_GetObjectItem(body, "bri");
bri = t->valueint;
printf("bri:%d\n", bri);
}
组装和解析是互逆的,但都是从顶cJSON对象开始开始一步步向下
main:
int main()
{
char *s;
//创建一个JSON
s = creatJson();
printf("创建的JSON(code101):\n");
printf("%s\n", s);
//解析刚才创建的JSON
printf("\n解析刚才创建的JSON(code101):\n");
parse_JSON(s);
}