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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM