#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;
}
cJSON用法示例
最新推荐文章于 2025-03-04 15:33:17 发布