C 语言之json库的使用

在C语言中,可以使用第三方库来解析和生成JSON数据。常用的JSON库包括cJSON和Jansson。

以下是使用cJSON库的示例代码:

  1. 安装cJSON库

首先需要下载并安装cJSON库。可以从官方网站下载源代码,并按照说明进行编译和安装。

  1. 包含头文件和使用cJSON库

在C语言代码中包含cJSON头文件,并使用cJSON库中的函数来解析和生成JSON数据。

#include   
#include   
#include "cJSON.h"  
  
int main() {  
    // 解析JSON数据  
    char *json_data = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";  
    cJSON *root = cJSON_Parse(json_data);  
    if (root == NULL) {  
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());  
        return 1;  
    }  
  
    // 获取JSON数据中的值  
    cJSON *name = cJSON_GetObjectItem(root, "name");  
    cJSON *age = cJSON_GetObjectItem(root, "age");  
    cJSON *city = cJSON_GetObjectItem(root, "city");  
    if (cJSON_IsString(name) && cJSON_IsNumber(age) && cJSON_IsString(city)) {  
        printf("Name: %s\n", cJSON_GetStringValue(name));  
        printf("Age: %d\n", cJSON_GetNumberValue(age));  
        printf("City: %s\n", cJSON_GetStringValue(city));  
    }  
  
    // 生成JSON数据  
    cJSON *person = cJSON_CreateObject();  
    cJSON_AddStringToObject(person, "name", "Alice");  
    cJSON_AddNumberToObject(person, "age", 25);  
    cJSON_AddStringToObject(person, "city", "San Francisco");  
    char *json_output = cJSON_Print(person);  
    printf("%s\n", json_output);  
    free(json_output);  
  
    // 释放内存  
    cJSON_Delete(root);  
    return 0;  
}

你可能感兴趣的:(C语言技术,json,c语言)