C語言中的JSON庫可以實(shí)現(xiàn)將JSON格式的數(shù)據(jù)轉(zhuǎn)換為C語言的數(shù)據(jù)結(jié)構(gòu)。而為了更好地對(duì)JSON數(shù)據(jù)進(jìn)行處理和使用,在C語言中也可以通過model轉(zhuǎn)換的方式將JSON數(shù)據(jù)轉(zhuǎn)換為對(duì)應(yīng)的C語言結(jié)構(gòu)體。關(guān)于這兩個(gè)轉(zhuǎn)換方式的具體實(shí)現(xiàn)可以看下面的代碼示例。
// JSON轉(zhuǎn)換為C語言結(jié)構(gòu)體 #include <stdio.h> #include <stdlib.h> #include <jansson.h> typedef struct { char *name; int age; char *address; } user; int main() { json_t *root; json_error_t error; root = json_loads("{\"name\":\"張三\", \"age\":18, \"address\":\"中國\"}", JSON_DECODE_ANY, &error); if (root) { user *us = (user *) malloc(sizeof(user)); memset(us, 0, sizeof(user)); us->name = (char*) json_string_value(json_object_get(root, "name")); us->age = json_integer_value(json_object_get(root, "age")); us->address = (char*) json_string_value(json_object_get(root, "address")); printf("name: %s\nage: %d\naddress: %s\n", us->name, us->age, us->address); free(us); } return 0; }
//C語言結(jié)構(gòu)體轉(zhuǎn)換為JSON #include <stdio.h> #include <jansson.h> typedef struct { char *name; int age; char *address; } user; int main() { user us = {"張三", 18, "中國"}; json_t *root = json_object(); json_object_set_new(root, "name", json_string(us.name)); json_object_set_new(root, "age", json_integer(us.age)); json_object_set_new(root, "address", json_string(us.address)); char *json_str = json_dumps(root, JSON_ENCODE_ANY | JSON_COMPACT); printf("%s\n", json_str); json_decref(root); free(json_str); return 0; }
以上兩個(gè)示例代碼便是C語言中實(shí)現(xiàn)JSON庫和model轉(zhuǎn)換的基礎(chǔ)操作。在實(shí)際開發(fā)中可以使用這兩種方法對(duì)JSON數(shù)據(jù)進(jìn)行自由轉(zhuǎn)換和操作,有助于更好地使用和處理JSON數(shù)據(jù)。