在c語言中,我們可以使用第三方庫或手動解析的方式接受json字符串。
第三方庫:
#include <stdio.h> #include <jansson.h> int main() { char *json_str = "{\"name\":\"Tom\",\"age\":18}"; json_t *root = NULL; json_error_t error; root = json_loads(json_str, 0, &error); if (!root) { printf("error: on line %d: %s\n", error.line, error.text); return 1; } json_t *name = json_object_get(root, "name"); json_t *age = json_object_get(root, "age"); printf("name: %s\n", json_string_value(name)); printf("age: %d\n", json_integer_value(age)); json_decref(root); return 0; }
手動解析:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 1024 int main() { char *json_str = "{\"name\":\"Tom\",\"age\":18}"; char *name = NULL; char *age = NULL; char *p = json_str + 1; while (*p != '}') { char key[MAX_LEN] = {0}; char value[MAX_LEN] = {0}; sscanf(p, "\"%[^\"]\":\"%[^\"]\"", key, value); if (strcmp(key, "name") == 0) { name = strdup(value); } else if (strcmp(key, "age") == 0) { age = strdup(value); } p = strchr(p, ',') + 1; } printf("name: %s\n", name); printf("age: %s\n", age); free(name); free(age); return 0; }