C Model轉換JSON 是一種常見的數據格式轉換方式,本文將介紹如何使用C語言編寫代碼將C Model轉換為JSON字符串。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <jansson.h> // C Model定義 typedef struct Student { char* name; int age; char* gender; bool isGraduated; } Student; // 將C Model轉換為JSON字符串 char* studentToJson(Student* student) { json_t* root = json_object(); json_object_set_new(root, "name", json_string(student->name)); json_object_set_new(root, "age", json_integer(student->age)); json_object_set_new(root, "gender", json_string(student->gender)); json_object_set_new(root, "isGraduated", json_boolean(student->isGraduated)); char* jsonStr = json_dumps(root, 0); json_decref(root); return jsonStr; } int main() { // 創建C Model對象 Student* student = (Student*)malloc(sizeof(Student)); student->name = "Tom"; student->age = 18; student->gender = "male"; student->isGraduated = false; // 將C Model轉換為JSON字符串 char* jsonStr = studentToJson(student); printf("%s\n", jsonStr); free(jsonStr); // 釋放C Model對象 free(student); return 0; }
以上代碼實現了將C Model轉換為JSON字符串的過程。需要注意的是,使用jansson庫需要在編譯時鏈接該庫,需要添加-ljansson參數。
上一篇python 視頻門哪好
下一篇vue多實體提交