在C語言中如何拼接JSON格式的字符串呢?
我們可以使用一個(gè)結(jié)構(gòu)體來表示一個(gè)JSON對(duì)象。假設(shè)要構(gòu)建以下JSON格式:
{ "name": "張三", "age": 20, "hobby": ["籃球", "游戲"] }
我們可以定義一個(gè)結(jié)構(gòu)體如下:
typedef struct { char* name; int age; char** hobby; int hobby_count; } Person;
JSON字符串拼接的方法通常是通過snprintf()
函數(shù)來實(shí)現(xiàn)。
拼接一個(gè)JSON對(duì)象的示例代碼如下:
void serialize_person(char* buffer, size_t buffer_size, Person* person) { snprintf(buffer, buffer_size, "{\"name\":\"%s\",\"age\":%d,\"hobby\":[", person->name, person->age); int i, remaining_size; char* buffer_pointer = buffer + strlen(buffer); for (i = 0; i< person->hobby_count; i++) { remaining_size = buffer_size - (buffer_pointer - buffer); snprintf(buffer_pointer, remaining_size, "\"%s\"", person->hobby[i]); buffer_pointer += strlen(buffer_pointer); if (i != person->hobby_count - 1) { snprintf(buffer_pointer, remaining_size, ","); buffer_pointer += 1; } } snprintf(buffer_pointer, remaining_size, "]}"); }
我們可以調(diào)用serialize_person()
函數(shù)來將一個(gè) Person 結(jié)構(gòu)體轉(zhuǎn)換為對(duì)應(yīng)的 JSON 字符串。示例代碼如下:
int main() { Person person; person.name = "張三"; person.age = 20; char* hobby[2] = {"籃球", "游戲"}; person.hobby = hobby; person.hobby_count = 2; char buffer[1024]; serialize_person(buffer, sizeof(buffer), &person); printf("%s\n", buffer); return 0; }
輸出:
{"name":"張三","age":20,"hobby":["籃球","游戲"]}
使用以上方法,我們可以輕松地在 C 語言中拼接 JSON 字符串。