json-c使用

精通使用json只需要会这几步即可:

1.json对象格式的分类:
2.json类型与对象的转换:
3.json的正删改查:
4.json的文件操作:
5.json的内存泄漏:

1.json对象格式的分类:

typedef enum json_type {
  /* If you change this, be sure to update json_type_to_name() too */
  json_type_null,     	//空类型      没有值或非下面几种类型  
  json_type_boolean,    //布尔类型    没咋用,欢迎大佬留言
  json_type_double,     //double类型  123.11  
  json_type_int,        //int类型     123
  json_type_object,     //json对象    {....} 
  json_type_array,      //数组类型     [,,,,]
  json_type_string,     //字符串类型    abc
} json_type;

2.json类型与对象的转换:待写
3.json的正删改查:待写
5.json的内存泄漏: 待写

4.json的文件操作:

 //文件内容返回json_type格式的对象
 struct json_object* json_object_from_file(const char *filename);
 //把json对象写入文件
 int json_object_to_file(const char *filename, struct json_object *obj);
 //下面这俩没咋用,欢迎大佬留言
 struct json_object* json_object_from_fd(int fd);
 int json_object_to_file_ext(const char *filename, struct json_object *obj, int flags);

1).json对象写入文件

 /*
 * writeFileJsonObj  json对象 写入file
 * new_obj : json 对象串 可以是多种格式
 * fileName:文件路径
 */
int writeFileJsonObj(const char *fileName,struct json_object *json_obj){
	int wriBool;
	if((json_obj == NULL)||(fileName == NULL)){
		return -1;
	}//1写入指定文件 --文件村不存在都可以 没有会创建
	wriBool = json_object_to_file(fileName,json_obj);
	return wriBool;
}

2).读取文件内容:

/*
 * ReadFileJson :读取json file  文件不存在创建
 * dataStr : 字符串
 * fileName:文件路径
 * return : json对象
 */
struct json_object *ReadFileJsonStr(const char *fileName){
	  struct json_object *json_obj = NULL;
    json_obj =  json_object_from_file(fileName); //读取文件
    return json_obj;
    }
//升级写法=如果文件里存的都是固定类型比如:json_type_object类型{...}
//可以多加一层判断
struct json_object *ReadFileJsonStr(const char *fileName){
	  struct json_object *json_obj = NULL;
    json_obj =  json_object_from_file(fileName); //读取文件
    if((json_obj != NULL)&&(json_type_object != json_object_get_type(json_obj))){
    cleanFile(fileName);//清除文件防止文件格式错误
    }
    return json_obj;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值