Cjson簡介與使用

json格式

  • json元素類型
	/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False  (1 << 0)
#define cJSON_True   (1 << 1)
#define cJSON_NULL   (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array  (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw    (1 << 7) /* raw json */
  • json數組
    • 中括號[整形,字符串,布爾類型,json數組,josn對象]
    • [123,123.4,true, false, [12,34,56,“hello”,“world”]]
    • 細節:最後一個元素是沒有逗號的
  • json 對象
    • { }中是一些鍵值對
      • {“name”:“ZhangSan”,
        “name”:“li4”}
      • key值:必須是字符串,且不重複
      • value值:可以使json對象,json數組,布爾,整形,字符串
  • json數組對象
  • json數組+json對象
    • {“name”:“ZhangSan”,
      “name”:“li4”,
      “張三”:{
      “別名”:“老王”,
      “性別”:“男”,
      “孩子”:"[“小紅”,“小黑”,“小白”]"
      }
      }

Cjson

  • 下載cjson-master.zip包,解壓命令 unzipt CJSON-master.zip
  • cJson對象
typedef struct cJSON
	{
		/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
		struct cJSON *next;
		struct cJSON *prev;
		/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
		struct cJSON *child;

		/* The type of the item, as above. */
		int type;

		/* The item's string, if type==cJSON_String  and type == cJSON_Raw */
		char *valuestring;
		/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
		int valueint;
		/* The item's number, if type==cJSON_Number */
		double valuedouble;

		/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
		char *string;
	} cJSON;
  • 創建一個json對象
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
{
    cJSON *item = cJSON_New_Item(&global_hooks);
    if (item) {
        item->type = cJSON_Object;
    }

    return item;
}
  • 往json對象中添加數據成員
CJSON_PUBLIC(void) cJSON_AddItemToObject(
cJSON *object,	//json對象,即上面創建的json對象 
const char *string, //key 
cJSON *item			//value(int,string, array, obj)
);
  • 創建一個整形值
cJSON *cJSON_CreateNumber(double num);
  • 創建一個字符串
cJSON *cJSON_CreateString(const char *string);

寫入json數據

{
	//json數據
	"奔馳"{
		"factory":"北京奔馳",
		"last":31,
		"price":83,
		"sell":49,
		"other":[123,
				true,
				"hello",
				{"梅賽德斯奔馳":"The best or nothing"}
				]
	}
}

int main()
{
	//創建對象
	cJSON *obj = cJSON_CreateObject();
	//創建以子對象
	cJSON *subobj=cJson_CreateObject();
	cJSON_AddItemToObject(subobj,"factory",cJSON_CreateString("北京奔馳"));
	cJSON_AddItemToObject(subobj,"last",cJSON_CreateNumber(31));
	cJSON_AddItemToObject(subobj,"price",cJSON_CreateNUmer(83));
	cJSON_AddItemToObject(subobj,"sell",cJSON_CreateNUmer(49));
	//創建一個空數組
	cJSON *array = cJSON_CreateArray();
	//數組中添加元素
	cJSON_AddItemToArray(array,cJSON_CreateNumber(123));
	cJSON_AddItemToArray(array,cJSON_CreateBool(1));
	cJSON_AddItemToArray(array,cJSON_CreateString("hello"));
	//數組中的對象
	cJSON *subsub = cJSON_CreateObject();
	cJSON_AddItemToObject(subsub,"梅賽德斯奔馳",cJSON_CreateString("The best or Nothing"));
	cJSON_AddItemToArray(array, subsub);
	cJSON_AddItemToObject(subobj,"other",array);
	//obj中添加鍵值對
	cJson_addItemtoObj("obj","奔馳",subobj);
	//數據格式化
	char *data = cJSON_Print(obj);
	FILE* fp = fopen("car.json","w");
	fwrite(data, sizeof(char), strlen(data)+1, fp);
	fclose(fp);
	
	return 0;
}	
  • 錯誤:在函數‘print_number’中:cJSON.c:對‘floor’未定義的引用
    將函數對應的庫加入 編譯時增加 -lm ,math庫

讀json數據

  • 將字符串解析爲json結構
//返回值需要使用cJSON_Delete釋放
(cJSON *) cJSON_Parse(
const char *value;
);
  • 根據json key查找
(cJSON *) cJSON_GetObjectItem(
const cJSON * const object, //當前json對象 
const char * const string   //key值
);

typedef struct cJSON
	{
		struct cJSON *next;
		struct cJSON *prev;
		struct cJSON *child;
		//重點在下面4行===========================
		int type; //The type of the item, as above.指向對頂端的類型
		
		char *valuestring;  //從這裏取 字符串
		int valueint;  	    //從這裏取 整形值
		double valuedouble; //從這裏取 浮點值
		//=======================================
		char *string;
	} cJSON;
  • 獲取json數組中的元素的個數
int cJSON_GetArraySize(cJSON *array);
  • 獲取數組下標找到對應的數組元素
cJSON *cJSON_GetArrayItem(cJSON *array,int index);
  • 判斷是否有可以值對應的鍵值對
//如果有這樣一個key, 如果有這樣一個key值 ,就會有一個value值
cJSON *cJSON_HasObjectItem(cJSON *object,const char* string);

在這裏插入圖片描述

  • 判斷數據
json = cJSON_Parse(topic_info->payload);
json_id = cJSON_GetObjectItem(json,id); 
if(json_id.type == cJSON_String) //判斷id鍵值的type是否是cJSON_String類型
{
	HAL_Printf("id:%s\r\n", json_id->valuestring);//獲取valuestring並打印
}
json_params = cJSON_GetObjectItem(json, "params");
if(json_params)
{
	json_led = cJSON_GetObjectItem(json_params, "led");
	if(json_led->type == cJSON_Number)  //判斷led鍵值的type是否是cJSON_Number類型
	{
		HAL_Printf("LED:%d\r\n", json_led->valueint);  //獲取valueint並打印
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章