C語言構(gòu)建JSON數(shù)據(jù)是一種十分方便的方式,因為C語言是一種強(qiáng)類型語言,可以更加精確地控制JSON數(shù)據(jù)的結(jié)構(gòu)和格式。
// 一個C語言的JSON結(jié)構(gòu)體 typedef struct json_object { int type; void *data; } json_object; // 一個JSON數(shù)據(jù)的例子 { "name": "小明", "age": 18, "hobby": ["籃球", "游戲"] } // 用C語言實現(xiàn)該JSON數(shù)據(jù) json_object *name = (json_object *)malloc(sizeof(json_object)); name->type = STRING_TYPE; name->data = "小明"; json_object *age = (json_object *)malloc(sizeof(json_object)); age->type = INT_TYPE; age->data = (void *)18; json_object *hobby = (json_object *)malloc(sizeof(json_object)); hobby->type = ARRAY_TYPE; hobby->data = (void *)malloc(2 * sizeof(json_object *)); ((json_object **)hobby->data)[0] = (json_object *)malloc(sizeof(json_object)); ((json_object **)hobby->data)[0]->type = STRING_TYPE; ((json_object **)hobby->data)[0]->data = "籃球"; ((json_object **)hobby->data)[1] = (json_object *)malloc(sizeof(json_object)); ((json_object **)hobby->data)[1]->type = STRING_TYPE; ((json_object **)hobby->data)[1]->data = "游戲"; json_object *result = (json_object *)malloc(sizeof(json_object)); result->type = OBJECT_TYPE; result->data = (void *)malloc(3 * sizeof(key_value_pair)); ((key_value_pair *)result->data)[0].key = "name"; ((key_value_pair *)result->data)[0].value = name; ((key_value_pair *)result->data)[1].key = "age"; ((key_value_pair *)result->data)[1].value = age; ((key_value_pair *)result->data)[2].key = "hobby"; ((key_value_pair *)result->data)[2].value = hobby;
以上代碼使用了自定義的JSON結(jié)構(gòu)體和鍵值對結(jié)構(gòu)體,通過動態(tài)內(nèi)存分配的方式申請了所需的空間,并為每個元素設(shè)置了類型和數(shù)據(jù)。使用這種方式可以避免手動構(gòu)建JSON字符串時的拼寫錯誤和格式問題。
上一篇c# json 接口
下一篇vue 跨域 nginx