Github Reference

DaveGamble/cJSON
Ref: Array(東小東)

cJSON_CreateObject()

cJSON *root; // or cJSON *root=NULL;
root = cJSON_CreateObject();

Create and Parse Sample

Add value into json


/* cjson sample */
{
	name : "Sarah Kinney",
	id : 23, 
	success : true 
}



static cJSON* createObjectSample() {
	// Create cJSON item
	cJSON *XRoot; 
	XRoot = cJSON_CreateObject();

	// Add String Type
	cJSON_AddStringToObject(XRoot, "name", "Sarah Kinney");

	// Add Number Type
	cJSON_AddNumberToObject(XRoot, "id", 23);

	// Add Boolean Type
	cJSON_AddBoolToObject(XRoot, "success", 1);

	return XRoot;
}


Add Object Into Object


/* cjson sample */
{
	Extra : {
		material : "Admantium"
	}
}


static cJSON* createObjectWithObjectSample() {
	cJSON *matRoot = NULL;
	matRoot = cJSON_CreateObject();
	if(NULL == matRoot) {
		fprintf(stderr, "The matRoot did not created.\n")
		return NULL;
	}
	cJSON *mat = NULL;
	mat = cJSON_CreateObject();
	if(NULL == mat) {
		fprintf(stderr, "The mat did not created.\n")
		cJSON_Delete(matRoot);
		return NULL;
	}
	cJSON_AddStringToObject(mat, "material", "Admantium");

	// Add mat into matRoot
	cJSON_AddItemToObject(matRoot, "Extra", mat);

	return matRoot;
}


cJSON_Print()

Print matRoot contain above sample.

char *ch = cJSON_Print(matRoot);
// or 
// char *ch = cJSON_PrintUnformatted(matRoot);

if(NULL == ch) {
	cJSON_Delete(matRoot);
	return NULL;
}
cJSON_Delete(matRoot);
...


// The "ch" contain json format.



Parse


/* parse json sample */
{
	Race : "Elf",
	Power : 203,
	Darkness : false,
	skill : {
		arrow : 6.7
	}

}


void parseJson(char *data) {
	if(NULL == date) return NULL;

	cJSON person = NULL;
	person = cJSON_Parse(data);
	if(NULL == person) {
		fprintf(stderr, "%s\n", "Parse Error.");
		return NULL;
	}

	// parse contain
	cJSON *pSub = NULL;

	pSub = cJSON_GetObjectItem(person, "Race");
	if(NULL == pSub) return NULL;
	printf("Race: %s", pSub->valuestring);

	pSub = cJSON_GetObjectItem(person, "Power");
	if(NULL == pSub) return NULL;
	printf("Power: %d", pSub->valueint);

	pSub = cJSON_GetObjectItem(person, "Darkness");
	if(NULL == pSub) return NULL;
	printf("Darkness: %d", pSub->valuebool);

	pSub = cJSON_GetObjectItem(person, "skill");
	if(NULL == pSub) return NULL;

	cJSON *pSubSub = NULL;
	pSubSub = cJSON_GetObjectItem(pSub, "arrow");
	if(NULL == pSubSub) {
		cJSON_Delete(pSub);
		return NULL;
	}
	printf("Arrow Level: %.1f", pSubSub->valuedouble);

	cJson_Delete(person);
}


Parse Boolean to condition

程式人生

/* parse boolean sample */
{
	success : True
}


void parseJsonSample(char* data) {
	cJSON *root = NULL;
	root = cJSON_Parse(data);
	if(NULL == root) return NULL;

	cJSON *succ = cJSON_GetObjectItemCaseSensitive(root, "success");

	if(cJSON_IsTrue(succ)) printf("Yes!");

	cJSON_Delete(root);
}