當(dāng)我們在使用C語言編寫json解析器時(shí),需要獲取數(shù)據(jù)類型,這是非常重要的一步。下面我們來看一下如何在C語言中獲取json數(shù)據(jù)的數(shù)據(jù)類型。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <cjson/cJSON.h> int main() { char *json_string = "{\"name\" : \"John\", \"age\" : 25, \"married\" : false, \"hobby\" : [\"reading\", \"swimming\"]}"; cJSON *json = cJSON_Parse(json_string); cJSON *name = cJSON_GetObjectItemCaseSensitive(json, "name"); if (cJSON_IsString(name) && (name->valuestring != NULL)) { printf("name : %s\n", name->valuestring); } cJSON *age = cJSON_GetObjectItemCaseSensitive(json, "age"); if (cJSON_IsNumber(age)) { printf("age : %d\n", age->valueint); } cJSON *married = cJSON_GetObjectItemCaseSensitive(json, "married"); if (cJSON_IsBool(married)) { printf("married : %s\n", married->valueint ? "true" : "false"); } cJSON *hobby = cJSON_GetObjectItemCaseSensitive(json, "hobby"); if (cJSON_IsArray(hobby)) { cJSON *hobby_item = NULL; cJSON_ArrayForEach(hobby_item, hobby) { if (cJSON_IsString(hobby_item) && (hobby_item->valuestring != NULL)) { printf("hobby : %s\n", hobby_item->valuestring); } } } cJSON_Delete(json); return 0; }
以上代碼中我們使用了cJSON庫來解析json數(shù)據(jù),通過cJSON_IsString()、cJSON_IsNumber()、cJSON_IsBool()、cJSON_IsArray()等函數(shù)來判斷json數(shù)據(jù)的數(shù)據(jù)類型,從而更加方便地進(jìn)行操作。