C语言库函数解析JSON文件

一、解析cJSON文件所需要的一些接口

1)根据键找json结点

/*Get item “string” from object*/ 从键得到值
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);

作用:获取JSON字符串字段值
返回值:成功返回一个指向cJSON类型的结构体指针,失败返回NULL

2)判断是否有key是string的项

extern int cJSON_HasObjectItem(cJSON *object,const char *string)

返回值:如果有返回1,否则否会0

3)返回数组结点array中成员的个数

extern int cJSON_GetArraySize(cJSON *array);

在这里插入图片描述
4)根据数组下标index取array数组结点的第index个成员,返回该成员节点

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

5)遍历数组

#define cJSON_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)

二、编写代码解析创建JSON文件

在这里插入图片描述
从键得到的值是什么类型? 这里我们要研究下cJSON的结构体:
我们可以知道通过type来确定类型

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;

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、分析代码

1、获取json对象中的一个元素:
cJSON *cJSON_GetObjectItem(json, “key”);

2、判断json对象中是否含有某一个元素:
cJSON_HasObjectItem(json, “key”);

3、node->type 判断对象的value类型,参看cJSON结构体

4、获取数组元素的个数:
cJSON_GetArraySize(nodeArr);

5、根据数组下标,获取元素:
cJSON_GetArrayItem(nodeArr, index);

6、遍历数组:
cJSON_ArrayForEach(tmpnode, nodeArr);

7、fopen fread(buf) fclose

发布了56 篇原创文章 · 获赞 3 · 访问量 2377

猜你喜欢

转载自blog.csdn.net/qq_40674996/article/details/102465756
今日推荐