- cJSON is a c/c++ lib for creating json or parsing json.
#include "cJSON.h"
1. Create Json Object/Array
cJSON* jobj = cJSON_CreateObject();
cJSON* jarr = cJSON_CreateArray();
2. Add items
cJSON_AddItemToObject(jobj, "arrName", jarr);
cJSON_AddStringToObject(jobj, "strName", "string");
cJSON_AddNumberToObject(jobj, "numName", 42);
cJSON_AddItemToArray(jarr, jobj);
3. Convert Json Object to a string
char* jsonStr = cJSON_Print(jobj);
- Note: remember to free after using
free(jsonStr);
4. Parse a string to Json Object
cJSON* proot = cJSON_Parse(jsonStr);
5. Get items
cJSON* pobj = cJSON_GetObjectItem(proot, "arrName");
string strValue = cJSON_GetObjectItem(jobj, "strName")->valuestring;
int numValue = cJSON_GetObjectItem(jobj, "numName")->valueint;
double floatValue = cJSON_GetObjectItem(jobj, "numName")->valuedouble;
cJSON* parr = cJSON_GetArrayItem(jarr, i);
int arrSize = cJSON_GetArraySize(jarr);