C语言解析JSON数值代码详解
假设我们有以下JSON字符串:
{
'name': 'John',
'age': 30,
'city': 'New York'
}
我们可以使用C语言解析JSON数值。首先,我们需要包含JSON解析器库。在本例中,我们将使用 cJSON 库。
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
接下来,我们需要读取JSON字符串并将其解析为 cJSON 对象。我们可以使用 cJSON_Parse 函数来完成这个任务。
char* json_string = "{'name':'John','age':30,'city':'New York'}";
cJSON* root = cJSON_Parse(json_string);
现在,我们可以通过 cJSON_GetObjectItem 函数获取每个数值。
cJSON* name = cJSON_GetObjectItem(root, 'name');
cJSON* age = cJSON_GetObjectItem(root, 'age');
cJSON* city = cJSON_GetObjectItem(root, 'city');
在本例中,我们的数值是整数,因此我们可以使用 cJSON_GetNumberValue 函数来获取它们的值。
printf("Name: %s\n", name->valuestring);
printf("Age: %d\n", (int)age->valuedouble);
printf("City: %s\n", city->valuestring);
最后,我们需要释放 cJSON 对象的内存。
cJSON_Delete(root);
以下是完整的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
char* json_string = "{'name':'John','age':30,'city':'New York'}";
cJSON* root = cJSON_Parse(json_string);
if (root == NULL) {
printf("Error parsing JSON: %s\n", cJSON_GetErrorPtr());
return 1;
}
cJSON* name = cJSON_GetObjectItem(root, 'name');
cJSON* age = cJSON_GetObjectItem(root, 'age');
cJSON* city = cJSON_GetObjectItem(root, 'city');
printf("Name: %s\n", name->valuestring);
printf("Age: %d\n", (int)age->valuedouble);
printf("City: %s\n", city->valuestring);
cJSON_Delete(root);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/otPs 著作权归作者所有。请勿转载和采集!