C語言可以通過結構體的方式來形成json格式的數據,具體的實現過程可以通過以下代碼進行演示:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <limits.h> #define BUFFER_SIZE 100 typedef struct { char *key; char *value; } KeyValue; typedef struct { char *type; char *name; int age; char *email; KeyValue *metadata; int metadataCount; } Person; int main(int argc, char *argv[]) { char buffer[BUFFER_SIZE]; Person person; KeyValue metadata[2]; // Initialize metadata metadata[0].key = "hobby"; metadata[0].value = "reading"; metadata[1].key = "occupation"; metadata[1].value = "developer"; // Initialize person person.type = "person"; person.name = "John Doe"; person.age = 30; person.email = "john.doe@example.com"; person.metadata = metadata; person.metadataCount = 2; // Serialize person as json snprintf(buffer, BUFFER_SIZE, "{" "\"type\":\"%s\"," "\"name\":\"%s\"," "\"age\":%d," "\"email\":\"%s\"," "\"metadata\":[" "{\"key\":\"%s\",\"value\":\"%s\"}," "{\"key\":\"%s\",\"value\":\"%s\"}" "]" "}", person.type, person.name, person.age, person.email, person.metadata[0].key, person.metadata[0].value, person.metadata[1].key, person.metadata[1].value); printf("%s\n", buffer); return 0; }
以上代碼演示了如何通過結構體的方式來存儲json格式的數據,并將其序列化為字符串輸出。這種方式可以讓我們在C語言中方便地處理json格式的數據,以便應用于各種場景。
上一篇dxp xml json
下一篇vue傳文件流