对于很多网络应用,json使用广泛。出于使用MQTT的使用,json好像更加方便。
#include "windows.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
/**
* json解析
*/
int main1(void)
{
/* 要解析的对象 */
char text[] = "{\"name\":\"jack\",\"eag\":23}";
/* print the version */
printf("Version: %s\n", cJSON_Version());
cJSON * json, * json_name, * json_eag;
json = cJSON_Parse(text);
json_name = cJSON_GetObjectItem(json, "name");
json_eag = cJSON_GetObjectItem(json, "eag");
if( (json == NULL)||(json_name == NULL)||(json_eag == NULL) )
{
printf("解析失败...\r\n");
system("pause");
}
printf("%s\r\n", json_name->valuestring);
printf("%d\r\n", json_eag->valueint);
// 释放内存空间
cJSON_Delete(json);
system("pause");
return 0;
}
/**
* 构建json
*/
int main(void)
{
/* 构建了一个{"name":"jack","eag":23} 的数据 */
cJSON * root;
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "name", cJSON_CreateString("jack"));
cJSON_AddItemToObject(root, "edg", cJSON_CreateNumber(23));
system("pause");
}