精通使用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;
    }
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐