cJSON用法示例

#include <stdlib.h>
#include <stdio.h>

#include <string>

#include "cJSON.h"


int main()
{
	printf("JSON Application.\r\n");
	
	std::string strJson = "";
	
	printf("...............................................\r\n");
	//打包成JSON字符串
	{
		cJSON *pJsonRoot = cJSON_CreateObject();
		cJSON *pArrayJson = cJSON_CreateArray();
		//添加元素
		cJSON_AddNumberToObject(pJsonRoot, "id", 0);
		cJSON_AddStringToObject(pJsonRoot, "str", "zab");
		cJSON_AddNumberToObject(pJsonRoot, "opt", 1);
		//添加子项
		cJSON *pJsonItem = cJSON_CreateObject();
		cJSON_AddNumberToObject(pJsonItem, "port", 8080);
		cJSON_AddStringToObject(pJsonItem, "ip", "127.0.0.1");
		cJSON_AddItemToArray(pArrayJson, pJsonItem);
		cJSON_AddItemToObject(pJsonRoot, "addr", pArrayJson);
		//输出字符串
		char *pcJsonStr = cJSON_Print(pJsonRoot);
		strJson = pcJsonStr;
		cJSON_Delete(pJsonRoot);
		if (NULL != pcJsonStr) {
			free(pcJsonStr);
			pcJsonStr = NULL;
		}
		printf("JSON=%s.\r\n", strJson.c_str());
	}
	printf("...............................................\r\n");
	
	//解析JSON字符串
	{
		struct MyAddr {
			std::string ip;
			int port;

			MyAddr() {
				ip = "";
				port = 0;
			}
		};
		struct MyInfo {
			int id;
			std::string str;
			int opt;
			MyAddr stAddr;

			MyInfo() {
				id = 0;
				str = "";
				opt = 0;
			}
		} stInfo;
		cJSON *pJson = cJSON_Parse(strJson.c_str());
		if (nullptr != pJson) {
			cJSON *pId = cJSON_GetObjectItem(pJson, "id");
			if (nullptr != pId) {
				stInfo.id = pId->valueint;
			}
			cJSON *pStr = cJSON_GetObjectItem(pJson, "str");
			if (nullptr != pStr) {
				stInfo.str = pStr->valuestring;
			}
			cJSON *pOpt = cJSON_GetObjectItem(pJson, "opt");
			if (nullptr != pOpt) {
				stInfo.opt = pOpt->valueint;
			}
			cJSON *pArray = cJSON_GetObjectItem(pJson, "addr");
			if (nullptr != pArray) {
				int nCount = cJSON_GetArraySize(pArray);
				for (int i = 0; i < nCount; ++i) {
					cJSON *pSub = cJSON_GetArrayItem(pArray, i);
					if (nullptr != pSub) {
						cJSON *pPort = cJSON_GetObjectItem(pSub, "port");
						if (nullptr != pPort) {
							stInfo.stAddr.port = pPort->valueint;
						}
						cJSON *pIp = cJSON_GetObjectItem(pSub, "ip");
						if (nullptr != pIp) {
							stInfo.stAddr.ip = pIp->valuestring;
						}
					}
				}
			}
			cJSON_Delete(pJson);
		}
		printf("my info id=%d,str=%s,opt=%d,ip=%s,port=%d.\r\n", \
			stInfo.id, stInfo.str.c_str(), stInfo.opt, \
			stInfo.stAddr.ip.c_str(), stInfo.stAddr.port);
	}
	printf("...............................................\r\n");
	
	printf("JSON Application End.\r\n");

	system("pause");

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值