番外篇10-cJSON库的使用

1.cJSON编译安装

  • github 地址:https://github.com/DaveGamble/cJSON
  • 下载

git clone https://github.com/DaveGamble/cJSON.git
参考 Readme 进行编译
可以直接使用 cJSON.h 和 cJSON.c 加入到源文件

  • 编译指令

gcc test.c cJSON.c -lm

2.数据结构定义

2.1cJSON结构

/* The cJSON structure: */
typedef struct cJSON
{
	/* next/prev allow you to walk array/object chains. Alternatively, use Get ArraySize/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;
	/* The item's number, if type==cJSON_Number */
	int valueint;
	/* The item's number, if type==cJSON_Number */
	double valuedouble;
12
	/* The item's name string, if this item is the child of, or is in the listof subitems of an object. */
	char *string;
} cJSON;

next、prev 用于遍历数组或对象链的前向后向链表指针;child 指向数组或对象的孩子节点;type 是 value 的类型;valuestring 是字符串值;valueint 是整数值;valuedouble是浮点数值;string 是 key 的名字。

2.2cJSON支持的类型

/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)	//布尔值:表示为true或者false。
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)		//null:空白可以加入到任何符号之间。
#define cJSON_Number (1 << 3)	//数值:一系列0--9的数字组合,可以为负数或者小数。还可以用”e”或者”E”表示为指数形式。数值(number)也与C或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。
#define cJSON_String (1 << 4)	//字符串:以""括起来的一串字符。字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。字符串(string)与C或者Java的字符串非常相似。
#define cJSON_Array (1 << 5)	//数组(Array):数组是值(value)的有序集合。一个数组以”[“(左中括号)开始,”]”(右中括号)结束。值之间使用”,”(逗号)分隔。数组索引从0开始。
#define cJSON_Object (1 << 6)	//对象(object):对象是一个无序的”名称/值”对集合。一个对象以”{“开始,并以”}”结束。每个”名称”后跟一个”:”(冒号)。”名称/值”对之间使用”,”(逗号)分隔。
#define cJSON_Raw (1 << 7) /* raw json */
  • valuestring,当类型为 cJSON_String 或 cJSON_Raw 时,value 的值,type 不符时为 NULL
  • valueint,当类型为 cJSON_Number 时,value 的值
  • valuedouble,当类型为 cJSON_NUmber 时,value 的值(主要用这个)
  • string, 代表 key,value 键值对中 key 的值

3.重点函数

3.1 cJSON_Parse

/* Supply a block of JSON, and this returns a cJSON object
you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
  • 作用:将一个 JSON 字符串,按照 cJSON 结构体的结构序列化整个数据包,并在堆中开辟一块内存存储 cJSON 结构体。(传入c语言的字符串)
  • 返回值:成功返回一个指向内存块中的 cJSON 的指针,失败返回 NULL。

3.2 cJSON_Delete

/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
  • 作用:释放位于堆中 cJSON 结构体内存。
  • 返回值:无
  • 注意:在使用 cJSON_Parse()获取 cJSON 指针后,若不再使用了,则需要调用 cJSON_Delete()对其释放,否则会导致内存泄漏。

3.3 cJSON_Print

/* Render a cJSON entity to text for transfer/storage.
Free the char* when finished. */
extern char *cJSON_Print(const cJSON *item);
  • 作用:将 cJSON 数据解析成 JSON 字符串,并在堆中开辟一块 char*的内存空间存储 JSON 字符串。cJSON_PrintUnformatted()与 cJSON_Print()类似,只是打印输出不带格式,而只是一个字符串数据。
  • 返回值:成功返回一个 char*指针该指针指向位于堆中 JSON 字符串,失败返回 NULL。
  • 注意:通过 cJSON_Print()可以将 cJSON 链表中所有的 cJSON 对象打印出来,但是需要手动去释放对应的资源:free(char *)。

3.4 cJSON_Version

/* returns the version of cJSON as a string */
extern const char* cJSON_Version(void);
  • 作用:获取当前使用的 cJSON 库的版本号。
  • 返回值:返回一个字符串数据。

3.5 cJSON_GetArrayItem

/* Retrieve item number "item" from array "array".
Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(const cJSON *array, int item);
  • 作用:从 object 的 cJSON 链中寻找 key 为 string 的 cJSON 对象。
  • 返回值:成功返回一个指向 cJSON 类型的结构体指针,失败返回 NULL。
  • 与 cJSON_GetObjectItem()类似的接口还有:
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(const cJSON *array);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(const cJSON *object, const char *string)
;
extern int cJSON_HasObjectItem(const cJSON *object, const char *string);

4.所有函数简介

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

5.使用范例介绍

1.测试文件1:cjson_test.c

  • 编译指令:gcc cJSON.c cjson_test.c -o cjson_test -lm
  • 文件内容

test1() //创建json文件,并解析
test2() //读取本地的json文件
test3() //对json增删查改

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
#include <string.h>

/**
{
	"name":	"milo",
	"age":	80,
	"professional": {专业
        "english": 4,
        "putonghua": 2,
        "computer": 4
    },
    "languages":	["C++", "C"],
	"phone":	{
		"number":	"18620823143",
		"type":	"home"
	},
	"courses":	[{
			"name":	"Linux kernel development",
			"price":	"7.7"
		}, {
			"name":	"Linux server development",
			"price":	"8.0"
		}],
	"vip":	true,
	"address":	null
}
*/

//打印CJSON
void printfJson(cJSON *json) {
    if (NULL == json) {
        return;
    }
    char *cjson=cJSON_Print(json);//深拷贝
    printf("json:%s\n", cjson);
    free(cjson);
}

//释放
void freeJson(cJSON *json) {
    if (json != NULL) {
        cJSON_Delete(json);
	}
}

//创建JSON
cJSON * createJson() {
    cJSON *json_root=cJSON_CreateObject();
	cJSON_AddItemToObject(json_root, "name", cJSON_CreateString("milo"));
	cJSON_AddNumberToObject(json_root, "age", 80);

    cJSON *json_professional=cJSON_CreateObject();
    cJSON_AddItemToObject(json_professional,"english", cJSON_CreateNumber(4));
    cJSON_AddItemToObject(json_professional,"putonghua", cJSON_CreateNumber(2));
    cJSON_AddItemToObject(json_professional,"computer", cJSON_CreateNumber(3));

    cJSON *json_languages=cJSON_CreateArray();
    cJSON_AddItemToArray(json_languages, cJSON_CreateString("C++"));
    cJSON_AddItemToArray(json_languages, cJSON_CreateString("C"));

    cJSON *json_phone=cJSON_CreateObject();
    cJSON_AddItemToObject(json_phone,"number", cJSON_CreateString("18620823143"));
    cJSON_AddItemToObject(json_phone,"type", cJSON_CreateString("home"));

    cJSON *json_courses = cJSON_CreateArray();
    cJSON* json_pItem1 = cJSON_CreateObject();
    cJSON_AddItemToObject(json_pItem1, "name", cJSON_CreateString("Linux kernel development"));
    cJSON_AddNumberToObject(json_pItem1, "price", 7.7);
    cJSON_AddItemToArray(json_courses, json_pItem1);

    cJSON* json_pItem2 = cJSON_CreateObject();
    cJSON_AddItemToObject(json_pItem2, "name", cJSON_CreateString("Linux server development"));
    cJSON_AddNumberToObject(json_pItem2, "price", 8.8);
    cJSON_AddItemToArray(json_courses, json_pItem2);


    cJSON_AddItemToObject(json_root, "professional", json_professional);
    cJSON_AddItemToObject(json_root, "languages", json_languages);
    cJSON_AddItemToObject(json_root, "phone", json_phone);
    cJSON_AddItemToObject(json_root, "courses", json_courses);

    cJSON_AddBoolToObject(json_root, "vip", 1);
    cJSON_AddNullToObject(json_root, "address");

    return json_root;
}

//已有JSON中添加
//"hobby": ["Basketball", "Football", "badminton"],
void addDataToJson(cJSON *json) {
    if (NULL == json) {
        return;
    }

    cJSON *hobby=cJSON_CreateArray();
    cJSON_AddItemToArray(hobby, cJSON_CreateString("Basketball"));
    cJSON_AddItemToArray(hobby, cJSON_CreateString("Football"));
    cJSON_AddItemToArray(hobby, cJSON_CreateString("badminton"));

    /*
    CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
    */
    cJSON_AddItemToObject(json, "hobby", hobby);

    printfJson(json);
}

//修改
//"hobby": ["Basketball", "Football", "badminton"],
//修改为
//"hobby": ["Skating", "dance"],
void updateDataToJson(cJSON *json) {
    if (NULL == json) {
        return;
    }

    cJSON *hobby=cJSON_CreateArray();
    cJSON_AddItemToArray(hobby, cJSON_CreateString("Skating"));
    cJSON_AddItemToArray(hobby, cJSON_CreateString("dance"));

    /*
    CJSON_PUBLIC(void) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
    CJSON_PUBLIC(void) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
    */
    cJSON_ReplaceItemInObject(json, "hobby", hobby);

    printfJson(json);
}

//删除
//"hobby": ["Skating", "dance"],
void deleteDataToJson(cJSON *json) {
    if (NULL == json) {
        return;
    }

    /*
    CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
    */
    cJSON_DetachItemFromObject(json, "hobby");

    printfJson(json);
}

//解析JSON
void analysisJsonObj(cJSON *json) {
    if (NULL == json) {
        return;
    }

    cJSON *json_name = cJSON_GetObjectItem(json, "name");
    printf("root[%s:%s]\n", json_name->string, json_name->valuestring);

    cJSON *json_age = cJSON_GetObjectItem(json, "age");
    printf("root[%s:%d]\n", json_age->string, json_age->valueint);

    cJSON *json_professional = cJSON_GetObjectItem(json, "professional");
    cJSON *json_professional_child = json_professional->child;
    while (json_professional_child != NULL) {
        printf("%s[%s:%d]\n", json_professional->string, json_professional_child->string, json_professional_child->valueint);
        json_professional_child = json_professional_child->next;

    }
    cJSON *json_languages = cJSON_GetObjectItem(json, "languages");
    if (json_languages) {
        int size = cJSON_GetArraySize(json_languages);
        printf("%s size:%d\n", json_languages->string, size);
        for (int i = 0; i < size; i++) {
            cJSON *json_languages_child =cJSON_GetArrayItem(json_languages, i);
            printf("%s[%d:%s]\n", json_languages->string, i, json_languages_child->valuestring);
        }
    }

    cJSON *json_phone = cJSON_GetObjectItem(json, "phone");
    cJSON *json_phone_number = cJSON_GetObjectItem(json_phone,"number");
    cJSON *json_phone_type = cJSON_GetObjectItem(json_phone,"type");
    printf("%s[%s:%s]\n", json_phone->string, json_phone_number->string, json_phone_number->valuestring);
    printf("%s[%s:%s]\n", json_phone->string, json_phone_type->string, json_phone_type->valuestring);

    cJSON *json_courses = cJSON_GetObjectItem(json, "courses");
    if (json_courses) {
        int size = cJSON_GetArraySize(json_courses);
        printf("%s size:%d\n", json_courses->string, size);
        for(int i=0;i<size;i++) {
            cJSON *json_array = cJSON_GetArrayItem(json_courses, i);
            if (json_array) {
                cJSON *json_course_name = cJSON_GetObjectItem(json_array,"name");
                cJSON *json_course_price = cJSON_GetObjectItem(json_array,"price");
                printf("%s[%s:%.1lf]\n", json_courses->string, json_course_name->string, json_course_name->valuedouble);
                printf("%s[%s:%.1lf]\n", json_courses->string, json_course_price->string, json_course_price->valuedouble);
            }
        }
    }

    cJSON *json_vip = cJSON_GetObjectItem(json, "vip");
    if (json_vip->type == cJSON_True) {
        printf("root[%s:true]\n", json_vip->string);
    } else if (json_vip->type == cJSON_False) {
        printf("root[%s:false]\n", json_vip->string);
    } else {
        printf("root[%s:false]\n", json_vip->string);
    }

    cJSON *json_address = cJSON_GetObjectItem(json, "address");
    if (json_address->type ==cJSON_NULL) {
        printf("root[%s:null]\n", json_address->string);
    }
}


static void printJsonObjvalue(const cJSON *json) {
    if (NULL == json) {
        printf("NULL object!\n");
        return;
    }

    switch (json->type) {
        case cJSON_False:
            printf("%s: false\n", json->string);
            break;
        case cJSON_True:
            printf("%s: true\n", json->string);
            break;
        case cJSON_NULL:
            printf("%s: cJSON_NULL\n", json->string);
            break;
        case cJSON_Number:
            printf("%s: %d, %f\n", json->string, json->valueint, json->valuedouble);
            break;
        case cJSON_String:
            printf("%s: %s\n", json->string, json->valuestring);
            break;
        case cJSON_Array:
            printf("%s: cJSON_Array\n", json->string);
            break;
        case cJSON_Object:
            printf("%s: cJSON_Object\n", json->string);
            break;
        default:
            printf("unknown type\n");
            break;
    }
}

void analysisJsonPrint(cJSON *json) {
    if (NULL == json) {
        return;
    }

    cJSON *json_name = cJSON_GetObjectItem(json, "name");
    printJsonObjvalue(json_name);

    cJSON *json_age = cJSON_GetObjectItem(json, "age");
    printJsonObjvalue(json_age);

    cJSON *json_professional = cJSON_GetObjectItem(json, "professional");
    cJSON *json_professional_child = json_professional->child;
    while (json_professional_child != NULL) {
        printJsonObjvalue(json_professional_child);
        json_professional_child = json_professional_child->next;
    }

    cJSON *json_languages = cJSON_GetObjectItem(json, "languages");
    if (NULL == json_languages) {
        int size = cJSON_GetArraySize(json_languages);
        printf("%s size:%d\n", json_languages->string, size);
        for (int i = 0; i < size; i++) {
            cJSON *json_languages_child = cJSON_GetArrayItem(json_languages, i);
            printJsonObjvalue(json_languages_child);
        }
    }

    cJSON *json_phone = cJSON_GetObjectItem(json, "phone");
    cJSON *json_phone_number = cJSON_GetObjectItem(json_phone,"number");
    cJSON *json_phone_type = cJSON_GetObjectItem(json_phone,"type");
    printJsonObjvalue(json_phone_number);
    printJsonObjvalue(json_phone_type);

    cJSON *json_courses = cJSON_GetObjectItem(json, "courses");
    if (json_courses) {
        int size = cJSON_GetArraySize(json_courses);
        printf("%s size:%d\n", json_courses->string, size);
        for(int i=0;i<size;i++) {
            cJSON *arrayItem = cJSON_GetArrayItem(json_courses, i);
            if (NULL != arrayItem) {
                cJSON *json_course_name = cJSON_GetObjectItem(arrayItem,"name");
                cJSON *json_course_price = cJSON_GetObjectItem(arrayItem,"price");
                printJsonObjvalue(json_course_name);
                printJsonObjvalue(json_course_price);
            }
        }
    }

    cJSON *json_vip = cJSON_GetObjectItem(json, "vip");
    printJsonObjvalue(json_vip);

    cJSON *json_address = cJSON_GetObjectItem(json, "address");
    printJsonObjvalue(json_address);
}

//读取JSON
cJSON* readJsonFile(char *fileName) {
    if (NULL == fileName) {
        return NULL;
    }

    FILE *fp = NULL;
    cJSON *json = NULL;
    char line[1024] = {0};
    char *data = NULL;

    //打开一个文本文件,文件必须存在,只允许读
    fp = fopen(fileName, "r");
    if (NULL != fp) {
        //seek末尾
        fseek(fp, 0, SEEK_END);
        //读取文件大小
        long len = ftell(fp);
        //seek起始位值
        fseek(fp, 0, SEEK_SET);
        data = (char*)malloc(len + 1);
        fread(data, 1, len, fp);
        fclose(fp);
    }
    
    printf("readJsonFile data:%s\n", data);
    cJSON *json_root = cJSON_Parse(data);
    if (NULL == json_root) {
        printf("cJSON_Parse error:%s\n", cJSON_GetErrorPtr());
    }

    if (NULL != data) {
        free(data);
    }

    return json_root;
}

//保存JSON
void writeJsonFile(char *fileName, cJSON *json) {
    if (NULL == json || NULL == fileName) {
        return;
    }

    char *cjson=cJSON_Print(json);

    FILE *fp = NULL;
    //新建一个文本文件,已存在的文件将内容清空,允许读写
    fp = fopen(fileName, "w+");
    if (NULL != fp) {
        fwrite(cjson, strlen(cjson),1,fp);
        fclose(fp);
	}

    if (NULL != cjson) {
        free(cjson);
	}
}

void test1() {//创建json文件,并解析
    cJSON *json_root = createJson();//创建json文件
    //打印
    printfJson(json_root);
    //解析json
    analysisJsonObj(json_root);
    //解析json
    analysisJsonPrint(json_root);
    freeJson(json_root);
}

void test2() {      //读取本地的json文件
    char *fileName = "./person.json";

    //读取json
    cJSON *json_root = readJsonFile(fileName);
    //解析json
    analysisJsonObj(json_root);
    //解析json
    analysisJsonPrint(json_root);

    //写入json文件
    writeJsonFile(fileName, json_root);

    //释放
    freeJson(json_root);
}

//增删改
void test3() {//对json增删查改
    cJSON *json_root = createJson();

    addDataToJson(json_root);

    updateDataToJson(json_root);

    deleteDataToJson(json_root);

    freeJson(json_root);
}

int main(int argc, char *argv[]) {
    
    // printf("-----------------------------------\n");
    // test1();
    printf("-----------------------------------\n");
    test2();
    printf("-----------------------------------\n");
    // test3();
    // printf("-----------------------------------\n");

    return 0;
}

json文件: person.json

{
	"name":	"milo",
	"age":	80,
	"professional":	{
		"english":	4,
		"putonghua":	2,
		"computer":	3
	},
	"languages":	["C++", "C"],
	"phone":	{
		"number":	"18620823143",
		"type":	"home"
	},
	"courses":	[{
			"name":	"Linux kernel development",
			"price":	7.700000
		}, {
			"name":	"Linux server development",
			"price":	8.800000
		}],
	"vip":	true,
	"address":	null
}

2.测试文件2:comment_test.c

  • 编译指令:gcc cJSON.c comment_test.c -o comment_test -lm
  • 文件内容

test1() //将comment结构体转化为json格式
test2() //读取本地的json文件

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "cJSON.h"
#include <string.h>


//评论
typedef struct COMMENT
{
    int user_id;
    int msg_id;
    char* comment;
    int click_count;
    int like_count;
    int reply_count;
    int is_new_reply;
    long add_time;
} COMMENT;

//获取当前时间毫秒数
long getCurrentTime()
{
    struct timeval tv;
    gettimeofday(&tv,NULL);
    //毫秒
    long time_sec = tv.tv_sec*1000 + tv.tv_usec/1000;

    return time_sec;
}

//打印CJSON
void printfJson(cJSON *json) {
    if (NULL == json) {
        return;
    }
    char *cjson=cJSON_Print(json);//深拷贝
    printf("json:%s\n", cjson);
    free(cjson);
}

void freeComment(COMMENT *comment) {
    if (comment != NULL) {
        if (comment->comment != NULL) {
            free(comment->comment);
            comment->comment = NULL;
        }

        free(comment);
        comment = NULL;
    }
}

void freeJson(cJSON *json) {
    if (json != NULL) {
        cJSON_Delete(json);
	}
}

/**
json对象
{
    "user_id":1,
    "msg_id":1,
    "comment":"json",
    "click_count":0,
    "like_count":0,
    "reply_count":0,
    "is_new_reply":0,
    "add_time":0,
}
*/

//将comment传过来后,创建json类
//将结构体转成cJSON
cJSON *convertToJson(COMMENT *comment) 
{
    if (comment == NULL) {
        return NULL;
    }

    //构建json
    //char *cjson = "{\"name\":\"milo\"}";//这样构建json,就需要使用cJSON_Parse()这个方法构建,将字符串解析成cJSON结构体
    //cJSON *json = cJSON_Parse(cjson);//这样创建的json有数据

    //创建json
    //将结构体转成json协议,保存或者提供给客户端
    cJSON *json=cJSON_CreateObject();//这样创建的json是没有数据的
    //将 "user_id" 添加到 "json" 节点. 
	cJSON_AddNumberToObject(json, "user_id", comment->user_id);//AddNumber指对应类型是数字类型的,数字类型包含整型和浮点型
	cJSON_AddNumberToObject(json, "msg_id", comment->msg_id);

    cJSON_AddItemToObject(json, "comment", cJSON_CreateString(comment->comment));//这里将结构体数据转为json
    cJSON_AddNumberToObject(json, "click_count", comment->click_count);
    cJSON_AddNumberToObject(json, "like_count", comment->like_count);
    cJSON_AddNumberToObject(json, "reply_count", comment->reply_count);
    cJSON_AddNumberToObject(json, "is_new_reply", comment->is_new_reply);
    cJSON_AddNumberToObject(json, "add_time", comment->add_time);

    return json;
}

//将cJSON赋值给结构体
//例如这里是客户端拿到服务器的json格式
COMMENT* convertToComment(cJSON *json)
{  
    if (NULL == json) {
        return NULL;
    }
   
    cJSON *json_user_id = cJSON_GetObjectItem(json, "user_id");
    cJSON *json_msg_id = cJSON_GetObjectItem(json, "msg_id");
    cJSON *json_comment = cJSON_GetObjectItem(json, "comment");
    cJSON *json_click_count = cJSON_GetObjectItem(json, "click_count");
    cJSON *json_like_count = cJSON_GetObjectItem(json, "like_count");
    cJSON *json_reply_count = cJSON_GetObjectItem(json, "reply_count");
    cJSON *json_is_new_reply = cJSON_GetObjectItem(json, "is_new_reply");
    cJSON *json_add_time = cJSON_GetObjectItem(json, "add_time");

    COMMENT *comment = (COMMENT *)malloc(sizeof(COMMENT));
    comment->user_id = json_user_id->valueint;
    comment->msg_id = json_msg_id->valueint;
    comment->comment=(char *)malloc(256);
    memset(comment->comment, 0, 256);
    strcat(comment->comment, json_comment->valuestring);
    comment->click_count = json_click_count->valueint;
    comment->like_count = json_like_count->valueint;
    comment->reply_count = json_reply_count->valueint;
    comment->is_new_reply = json_is_new_reply->valueint;
    comment->add_time = (long)(json_add_time->valuedouble);

    return comment;
}

//从文件中读取到json
void readJsonFromData(char *data) {
    cJSON *json=cJSON_Parse(data);              //将data数据构建成cJSON结构
    //打印json
    printfJson(json);                           //打印json   

    COMMENT* comment = convertToComment(json);  //类似拆json包,例如这里是客户端拿到服务器的json格式
    if (comment != NULL) {
        
        comment->like_count = 77;               //
        comment->reply_count = 99;              //

        //转为json
        cJSON *childjson = convertToJson(comment);
        //打印json
        printfJson(childjson);
        //释放对象
        freeComment(comment);
        //
        freeJson(childjson);
	}
    freeJson(json);
}

//保存JSON
void writeJsonFile(cJSON *json) {
    if (NULL == json) {
        return;
    }

    char *cjson=cJSON_Print(json);

    FILE *fp = NULL;
    char *fileName = "./comment.json";
    fp = fopen(fileName, "w+");
    if (NULL != fp) {
        fwrite(cjson, strlen(cjson),1,fp);
        fclose(fp);
	}
    if (cjson != NULL) {
        free(cjson);
	}
}

//读取JSON
void readJsonFile() {
    FILE *fp = NULL;
    char *out;
    char line[1024] = {0};
    char *fileName = "./comment.json";

    //打开一个文本文件,文件必须存在,只允许读
    fp = fopen(fileName, "r");
    //seek末尾
    fseek(fp, 0, SEEK_END);
    //读取文件大小
    long len = ftell(fp);
    //seek起始位值
    fseek(fp, 0, SEEK_SET);
    char *data = (char*)malloc(len + 1);
    fread(data, 1, len, fp);
    if (fp != NULL) {
        fclose(fp);
	}

    //读取
    readJsonFromData(data);
    
    if (NULL != data) {
        free(data);
    }
}

//获取了一个comment的对象
COMMENT *createComment() {
    COMMENT *comment = (COMMENT *)malloc(sizeof(COMMENT));
    comment->user_id = 1;
    comment->msg_id = 10000;
    comment->comment=(char *)malloc(256);
    memset(comment->comment, 0, 256);
    sprintf(comment->comment, "我赞同楼主");
    comment->click_count = 0;
    comment->like_count = 0;
    comment->reply_count = 0;
    comment->is_new_reply = 0;
    comment->add_time = getCurrentTime();
    return comment;
}

void test1() {
    COMMENT *comment = createComment();//创建comment对象,就是数据包结构体初始化

    //转为json
    cJSON *json = convertToJson(comment);//将结构体转成cJSON,返回json对象
    
    //保存json
    writeJsonFile(json);//把json保存到本地

    freeComment(comment);//释放结构体数据

    freeJson(json);//
}

void test2() {
    //读取json
    readJsonFile();
}

int main(int argc, char *argv[]) {
    
    test1();

    test2();

    return 0;
}

json文件: comment.json

{
	"user_id":	1,
	"msg_id":	10000,
	"comment":	"我赞同楼主",
	"click_count":	0,
	"like_count":	0,
	"reply_count":	0,
	"is_new_reply":	0,
	"add_time":	1624628790079
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值