cJSON的简单使用

对于很多网络应用,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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值