C語言作為一門底層語言,獲取Json節點值需要借助第三方庫,如cJSON庫。
#include <stdio.h> #include <cJSON.h> int main() { char *jsonstr = "{\"name\":\"Tom\",\"age\":18,\"score\":[89,96,87],\"address\":{\"city\":\"Beijing\",\"street\":\"Tiananmen Square\"}}"; cJSON *root = cJSON_Parse(jsonstr); //獲取String值 cJSON *name = cJSON_GetObjectItem(root, "name"); printf("name is %s\n", name->valuestring); //獲取Int值 cJSON *age = cJSON_GetObjectItem(root, "age"); printf("age is %d\n", age->valueint); //獲取Array值 cJSON *score = cJSON_GetObjectItem(root, "score"); cJSON *s1 = cJSON_GetArrayItem(score, 0); cJSON *s2 = cJSON_GetArrayItem(score, 1); cJSON *s3 = cJSON_GetArrayItem(score, 2); printf("score is %d,%d,%d\n", s1->valueint, s2->valueint, s3->valueint); //獲取Object值 cJSON *address = cJSON_GetObjectItem(root, "address"); cJSON *city = cJSON_GetObjectItem(address, "city"); cJSON *street = cJSON_GetObjectItem(address, "street"); printf("address is %s,%s\n", city->valuestring, street->valuestring); cJSON_Delete(root); return 0; }
通過cJSON庫提供的函數,我們可以輕松地獲取Json節點的各種值。