cJSON使用记录

下cJSON的结构体,用于描述一个键值对,在cJSON的API里Object和item都是用这个结构体描述。但是item包含了名字,Object没有名字,就用大括号括起来。

/* 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;

其中比较早重要的就是

struct cJSON *next;

用来链接下一个tiem结构体,也就是同一个大括号内的下一个键值对,Item。

struct cJSON *child

用来描述下一级大括号内的整个Object。

int type;
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False  (1 << 0)
#define cJSON_True   (1 << 1)
#define cJSON_NULL   (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array  (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw    (1 << 7) /* raw json */

类型,其中的False和True经常使用。

    /* 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;

这个是Item的名字,也就是大括号前的名字。

一些常用的API:

一、创建JSON

cJSON_CreateObject()

用来创建一个Object,没有名字,类似于:

{

}

cJSON_AddxxxxxxToObject

向一个Object添加一个xxx,带名字

{

        "name":value

}

cJSON_AddItemToObject

向Object中添加一个Item,带名字,结果

{

        "Item":

        {

        }

}

cJSON_CreateArray()

创建一个array,类似于

"arrayName":[ ]

cJSON_AddItemToArray

向array添加一个Item,没有名字,结果

"arrayName":[ {"name": value } ]

(这个叫 cJSON_AddObjectToArray是不更好)

cJSON_Createxxx()

除了创建Item和Object,还能直接创建number,string等类型,没有名字的,一般用于向array添加成员。

cJSON_PrintUnformatted()

将创建的cJSON链表输出到一片内存区域,去掉了回车和空格,自动通过malloc申请的内存,返回指针。

二、解析JSON

cJSON_Parse

将一串字符串解析成JSON链表。失败返回NULL;

cJSON_GetObjectItem

从一个Object中获取一个指定的Item,以名字进行区分。成功返回cJSON指针。

也就是从大括号里拿出一个键值对。

cJSON_GetArrayItem

从array里按索引拿出一个Item。

几个注意事项:

1.使用完cJSON并且打印出字符串以后需要释放掉cJSON占用的内存。使用cJSON_Delete直接释放掉根节点即可。

2.打印出的字符串内存也需要free掉;

3.使用cJSON解析字符串以后也需要cJSON_Delete释放掉根节点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值