Maxbad`Blog

cjson 使用记录

2020-07-25 · 2 min read

备忘

打印

cJSON_Print会申请内存,使用完后要free掉。

	const  char* pstr = cJSON_Print(json);
	free(pstr);

cJSON_PrintUnformatted 打印出的json字符串是紧凑的不用换行,适合传输json字符串时使用
cJSON_PrintBuffered 可以事先指定分配一个缓冲区,如果足够大,则可以节省不断重新分配空间的时间; 如果指定缓冲区过小,则与cJSON_Print和cJSON_PrintUnformatted性能能相同。
cJSON_PrintPreallocated 可以将json字符串填入给定的缓冲区,并指定缓冲区大小。 成功返回1,失败返回0。除了这个打印json字符串的函数,以上的函数在生成json字符串时若空间不足,都会重新分配一次空间。

销毁

JSON对象使用完成记得Delete

	cJSON* pjson = NULL;
	pjson = cJSON_Parse("{}");
	cJSON_Delete(pjson);

解析

cJSON_ParseWithOpts该函数是cJSON_Parse的实现,但是它比cJSON_Parse更灵活。

  • 如果cJSON_Parse解析错误,必须调用cJSON_GetErrorPtr找到解析错误位置
  • cJSON_Parse解析不严谨,如"{\"name\": \"Lee\"} }"这个字符串,后边多了一个大括号,但还是解析成功了。
  • cJSON_ParseWithOpts的return_parse_end参数可以获取解析失败的位置, require_null_terminated参数为1会检查剩余未解析字符串是否是空字符串,若不为空字符串,则会释放内存,返回空。所以因该使用cJSON_ParseWithOpts解析json对象
	char* end = NULL;
	cJSON* cj_ParseWithOpts = cJSON_ParseWithOpts("{\"name\": \"Lee\"} }", &end, 1);
	if (cj_ParseWithOpts) {
		printf("%s\n\n", cJSON_Print(cj_ParseWithOpts));
	}
	else {
		printf("[%s]\n\n", end);
	}

数组倒删除

	cJSON* adArr = NULL;  //欲删除的数组
	int arrCount = cJSON_GetArraySize(adArr);
	if (arrCount > 0)
	{
		for (int j = arrCount - 1; j >= 0; j--)
		{
			cJSON_DeleteItemFromArray(adArr, j);  //删除json数组对象的第j个节点
		}
	}

对象替换

 cJSON* itemObj = NULL;  

   //文本替换
   cJSON_ReplaceItemInObject(itemObj, "username", cJSON_CreateString("tom"));

   //数组清空
   cJSON_ReplaceItemInObject(itemObj, "userlist", cJSON_CreateArray());