本文通过简单示例展示使用cJSON库进行JSON构造和解析的方法。
构造的json字符串为:{"num":0,"str":"teststring"}
#include <stdio.h>
#include "cjson\cJSON.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
//构造
cJSON *json = cJSON_CreateObject();
cJSON_AddNumberToObject(json, "num", 0);
cJSON_AddStringToObject(json, "str", "teststring");
//打印
char* out = cJSON_Print(json);//有格式
//char* out = cJSON_PrintUnformatted(json);//无格式
printf("%s\n", out);
//解析
cJSON *json_parse = cJSON_Parse(out);
cJSON *sub = cJSON_GetObjectItem(json_parse, "num");
cJSON *sub2 = cJSON_GetObjectItem(json_parse, "str");
int num = sub->valueint;
string str = sub2->valuestring;
cout << "num=" << num << endl;
cout << "str = " << str << endl;
return 0;
}