JSON是使用廣泛的輕量級(jí)數(shù)據(jù)交換格式,C語(yǔ)言中使用CJSON庫(kù)來(lái)解析和生成JSON數(shù)據(jù)格式。以下是一些CJSON的實(shí)例,包含了JSON對(duì)象的創(chuàng)建、JSON字符串的解析和JSON對(duì)象的訪(fǎng)問(wèn)。
//創(chuàng)建JSON對(duì)象 cJSON * root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "name", "Lucy"); cJSON_AddNumberToObject(root, "age", 26); cJSON_AddTrueToObject(root, "isStudent"); //JSON字符串解析 char * jsonString = "{\"name\":\"Tom\",\"age\":30,\"isStudent\":false}"; cJSON * root = cJSON_Parse(jsonString); char * name = cJSON_GetObjectItem(root, "name")->valuestring; int age = cJSON_GetObjectItem(root, "age")->valueint; bool isStudent = cJSON_GetObjectItem(root, "isStudent")->valueint; //JSON對(duì)象訪(fǎng)問(wèn) cJSON * root = cJSON_CreateObject(); cJSON * hobbyArray = cJSON_CreateArray(); cJSON_AddItemToObject(root, "hobby", hobbyArray); cJSON * hobby1 = cJSON_CreateString("Reading"); cJSON * hobby2 = cJSON_CreateString("Travelling"); cJSON_AddItemToArray(hobbyArray, hobby1); cJSON_AddItemToArray(hobbyArray, hobby2); int arraySize = cJSON_GetArraySize(hobbyArray); for (int i = 0; i< arraySize; i++) { cJSON * hobby = cJSON_GetArrayItem(hobbyArray, i); char * hobbyStr = cJSON_GetObjectItem(hobby, "hobby")->valuestring; printf("%s\n", hobbyStr); }
上述實(shí)例展示了CJSON庫(kù)的一些基本使用方法,包括JSON對(duì)象的創(chuàng)建、JSON字符串的解析和JSON對(duì)象的訪(fǎng)問(wèn)。通過(guò)CJSON庫(kù)的支持,我們可以在C語(yǔ)言中輕松地進(jìn)行JSON數(shù)據(jù)的操作和交換,為各種數(shù)據(jù)應(yīng)用提供更加靈活和高效的數(shù)據(jù)格式支持。