【C语言之 CJson】学CJson看这一篇就够了

【C语言之 CJson】学CJson看这一篇就够了CJSON 是一个轻量级的 用于处理 JSON 数据的 C 语言库

大家好,欢迎来到IT知识分享网。


前言

CJSON 是一个轻量级的、用于处理 JSON 数据的 C 语言库。它提供了简单而直观的 API,使得在 C 程序中处理 JSON 数据变得相对容易。在本文中,我们将介绍 CJSON 的基本使用,包括如何创建 JSON 对象、解析 JSON 字符串、访问 JSON 数据以及释放相关资源。


一、下载CJson

点击去下载好的文件后,我们只需要其中的cJSON.c和cJSON.h文件即可。

在这里插入图片描述
只需要在我们main里面包含cJSON.h即可

二、创建一个json

2.1 创建json对象

在我们的json中,他的结构如下:

{ 
      ... } 

外面的大括号就是我们的root,我们就先创建他才能进行后续的操作

函数原型:

CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); 

无参数,返回值为cJSON 的指针

cJSON类型详解

cJson结构体如下定义:

/* The cJSON structure: */ typedef struct cJSON { 
      /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ struct cJSON *next; struct cJSON *prev; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ struct cJSON *child; /* The type of the item, as above. */ int type; /* The item's string, if type==cJSON_String and type == cJSON_Raw */ char *valuestring; /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ int valueint; /* The item's number, if type==cJSON_Number */ double valuedouble; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ char *string; } cJSON; 

这是 cJSON 库中定义的结构体 cJSON,它用于表示 JSON 数据的各个部分。以下是各个成员的解释:

next/prev:

child:

type:

valuestring:

valueint:

valuedouble:

string:

2.2 创建键值对

使用下面这个函数即可创建一个键值对

CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) 

这个函数是 cJSON 库中的一个函数,用于向一个 JSON 对象(或者说 JSON 字典)中添加一个字符串类型的键值对。

这是一个指向 JSON 对象的指针,表示你要往哪个对象中添加键值对。

2.3 添加嵌套的 JSON 对象

使用下面这个函数为添加嵌套的json对象

CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) 

返回值:

2.4 添加数组

创建数组

CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); 

无参数,返回值为cJSON,这个数组的指针

添加元素到数组

CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); 

参数:

添加数组到obj

CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) 

这个函数是 cJSON 库中的一个函数,用于向一个 JSON 对象(或者说 JSON 字典)中添加一个 JSON 元素。

2.5 将 JSON 对象转为字符串

使用下面这个函数就可以把你的json转换成字符串了

CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); 

2.6 释放内存

使用下面这个函数即可释放我们的内存

CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) 

参数一般填我们的root

2.7 示例代码

#include <stdio.h> #include <stdlib.h> #include "cJSON.h" char Json[1024] = { 
      '\0' }; void ReadJson() { 
      FILE* f = NULL; fopen_s(&f, "learn.json", "r"); fread(Json, 1, 1023, f); printf("%s\n", Json); fclose(f); } int main() { 
      // 创建 JSON 对象 cJSON* root = cJSON_CreateObject(); // 添加基本键值对 cJSON_AddStringToObject(root, "name", "John"); cJSON_AddNumberToObject(root, "age", 30); // 添加嵌套的 JSON 对象(地址) cJSON* address = cJSON_CreateObject(); cJSON_AddStringToObject(address, "street", "123 Main St"); cJSON_AddStringToObject(address, "city", "Anytown"); cJSON_AddStringToObject(address, "postalCode", "12345"); cJSON_AddItemToObject(root, "address", address); // 添加数组 cJSON* interests = cJSON_CreateArray(); cJSON_AddItemToArray(interests, cJSON_CreateString("Reading")); cJSON_AddItemToArray(interests, cJSON_CreateString("Gardening")); cJSON_AddItemToArray(interests, cJSON_CreateString("Cooking")); cJSON_AddItemToObject(root, "interests", interests); // 将 JSON 对象转为字符串 char* jsonString = cJSON_Print(root); printf("JSON Object:\n%s\n", jsonString); // 释放内存 cJSON_Delete(root); free(jsonString); return 0; } 

在这里插入图片描述

三、解析json

3.1 解析json root

使用下面这个函数,就可以把一个const char *的字符串解析成cJSON对象了

CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); 

检测是否解析成功:

if (root == NULL) { 
      const char* error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { 
      fprintf(stderr, "Error before: %s\n", error_ptr); } return 1; // Exit with an error code } 

在这里插入图片描述

3.2 把一个key解析出来变成cJSON对象

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) 

参数:

3.3 判断cJSON的存储的类型

在CJSON中有这么一些函数,他的参数为cJson指针类型,用他们可以判断里面是什么类型的,以便后续的操作

/* These functions check the type of an item */ CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); 

在这里插入图片描述

3.4 获取键值对的值

在CJSON中有这两个函数,他们的参数为cJSON指针对象,返回值为值

/* Check item type and return its value */ CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); 

在这里插入图片描述

int age_value = age->valueint; 

3.5 获取和遍历数组

获取数组里面指定index的值

使用下面这个函数即可获取指定index的cJson类型了

CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); 

在这里插入图片描述

获取数组的大小

使用下面这个函数就可以获取array里面有几个元素了

/* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); 

在这里插入图片描述

遍历数组

cJSON* scores = cJSON_GetObjectItemCaseSensitive(root, "scores"); if (cJSON_IsArray(scores)) { 
      int array_size = cJSON_GetArraySize(scores); printf("Scores: "); for (int i = 0; i < array_size; i++) { 
      cJSON* score_element = cJSON_GetArrayItem(scores, i); if (cJSON_IsNumber(score_element)) { 
      printf("%d ", score_element->valueint); } } printf("\n"); } 

在这里插入图片描述


总结

CJSON 提供了一个简单而功能丰富的方式来处理 JSON 数据。通过创建 JSON 对象、数组,以及使用相应的函数来填充和访问数据,你可以在 C 语言中轻松地进行 JSON 操作。在使用 cJSON 时,记得及时释放分配的内存以避免内存泄漏。

这篇文章提供了一个基本的入门指南,希望能够帮助你开始使用 CJSON 在 C 语言中处理 JSON 数据。如果你有更复杂的需求,建议查看 cJSON 的文档和示例代码,以更深入地了解其功能和用法。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/109919.html

(0)
上一篇 2026-02-03 21:45
下一篇 2026-02-03 22:10

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注微信