C語言是一門廣泛應用的編程語言,其數據類型多樣,開發者往往需要進行各種數據格式的轉換。如何將C類對象轉換為JSON格式呢?
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <stdint.h> #include <stddef.h> #include <picojson.h> typedef struct _Student { char name[20]; int age; bool is_male; struct _Student* next; } Student; const char *to_json(const void *object, size_t size) { const picojson::value v(to_json_object(object, size)); std::string s = v.serialize(); const char *c = s.c_str(); char *result = (char*)malloc(strlen(c) + 1); strcpy(result, c); return result; } picojson::value to_json_object(const void *object, size_t size) { if (object == NULL || size == 0) { return picojson::value(); } Student *student = (Student*)object; picojson::object obj; obj["name"] = picojson::value(student->name); obj["age"] = picojson::value((double)student->age); obj["is_male"] = picojson::value(student->is_male); obj["next"] = to_json_object(student->next, sizeof(Student)); return picojson::value(obj); } int main() { Student s1 = {"Tom", 18, true, NULL}; Student s2 = {"Jerry", 17, false, &s1}; const char *json_str = to_json(&s2, sizeof(Student)); printf("JSON: %s\n", json_str); return 0; }
上述代碼通過picojson庫實現了將C類對象轉換為JSON格式的功能。to_json_object方法遞歸調用了屬性的to_json_object方法,實現了對鏈表結構的JSON轉換。to_json方法則是將picojson::value對象序列化為字符串,最終返回C風格的字符串。