C++使用cJSON

C++使用cJSON

C++中使用的JSON库没有C#中使用json库好用,写惯了C#,现在写C++的json,很难受。这里记录一下C++使用cJSON的用法。

将cJSON.cpp和cJSON.h添加到项目中即可。

一、数组构建操作

cJSON* json = cJSON_CreateArray();//创建一个数组

	cJSON* item = cJSON_CreateBool(true);

	cJSON_AddItemToArray(json, item);//添加数组元素

	item = cJSON_CreateBool(false);

	cJSON_AddItemToArray(json, item);
	char* ch = cJSON_Print(json); //序列化json字符串
	int size = cJSON_GetArraySize(json); //返回数组元素个数

	cJSON_Delete(json);//空间释放

二、数组读取操作

cJSON* json = cJSON_Parse("[1,2,3,4]");//加载json字符串

	if (cJSON_IsArray(json))
	{
		int size = cJSON_GetArraySize(json);
		for (int i = 0; i < size; i++)
		{
			cJSON* item = cJSON_GetArrayItem(json, i);
			if (cJSON_IsNumber(item))
			{
				cout << item->valueint << endl;
			}
		}
	}
	cJSON_Delete(json);

二、对象构建操作

cJSON* json = cJSON_CreateObject();//创建对象
	cJSON_AddStringToObject(json, "name", "张三");
	cJSON_AddBoolToObject(json, "man", true);
	cJSON_AddNumberToObject(json, "age", 18);
	
	cJSON* item1 = cJSON_CreateArray();
	cJSON_AddItemToArray(item1, cJSON_CreateNumber(11));
	cJSON_AddItemToArray(item1, cJSON_CreateNumber(12));
	cJSON_AddItemToArray(item1, cJSON_CreateNumber(13));

	cJSON_AddItemToObject(json, "days", item1);//添加数组

	cJSON* item2 = cJSON_CreateObject();
	cJSON_AddStringToObject(item2, "address", "中国");
	cJSON_AddStringToObject(item2, "phone", "189");

	cJSON_AddItemToObject(json, "info", item2);//添加对象
	char* ch = cJSON_Print(json);
	cJSON_Delete(json); 

三、对象读取操作

cJSON* json = cJSON_Parse("{"name":"zzr","age":[1,2,3,60]}");//加载json字符
	if (json != nullptr)
	{
		cJSON* item = cJSON_GetObjectItem(json, "name");//读取name字段
		if (cJSON_IsString(item))
		{
			cout << item->valuestring << endl;
		}
		item = cJSON_GetObjectItem(json, "age");//读取age字段
		if (item != nullptr && cJSON_IsArray(item)) //判断为是数组
		{
			int size = cJSON_GetArraySize(item);
			for (int i = 0; i < size; i++)
			{
				cJSON* arrayItem = cJSON_GetArrayItem(item, i);
				if (arrayItem != nullptr && cJSON_IsNumber(arrayItem))
				{
					cout << arrayItem->valueint << endl;
				}
			}
		}
	}
	else
	{
		const char* error = cJSON_GetErrorPtr();//错误提示
		cout << error << endl;
	}
	cJSON_Delete(json);
原文地址:https://www.cnblogs.com/zzr-stdio/p/14447526.html