cJson 创建 读取

http://blog.sina.com.cn/s/blog_5f28333901017kql.html

关于c语言操作json,cjson还挺好用,许多操作已经帮开发员封装好了,使用起来很方便。资源下载地址为:http://sourceforge.net/projects/cjson/

在test.c文件中已经有很多例子,看了还不会使用可以直接看cjson.c文件,也不深奥,实际上就是个双链表,然后是对这个双链表进行增删改查
记录下这两天运用到的

现有一个json文件如下:
[
{
"id": "c1",
"option": "install",
"fid": "1"},
{
"id": "p1",
"option": "notinstall",
"fid": "2"
}
]

1. 读取一个json文件,返回json结构链表,注意,这里返回值必须为cJSON*,具体原因看上一篇文章。另外关于json的介绍看, http://www.json.org/json-zh.html

cJSON* GetJsonObject(char* fileName, cJSON* json)
{
       long len;
       char* pContent;
       int tmp;
       FILE* fp = Open_File(fileName, "rb+");
       if(!fp)
       {
              return NULL;
       }
       fseek(fp,0,SEEK_END);
       len=ftell(fp);
       if(0 == len)
       {
              return NULL;
       }
     
       fseek(fp,0,SEEK_SET);
       pContent = (char*) malloc (sizeof(char)*len);
       tmp = fread(pContent,1,len,fp);

       Close_File(fp);
       json=cJSON_Parse(pContent);
       if (!json)
       {
              return NULL;
       }
       free(pContent);
       return json;
}


2 读取cJSON索引为index的结点某个key值对应的value,索引从0开始

BOOL GetValueString(cJSON* json,int id, char* name, char* param)
{
       cJSON* node;
       node = cJSON_GetArrayItem(json,id);
       if(!node)
       {
              return FALSE;
       }
       sprintf(param, "%s", cJSON_GetObjectItem(node, name)->valuestring);
       return TRUE;
}
比如读取id=1,name="name",得到param为"notinstall"

3 生成json文件
void Create_Pkgs(char* option1, char* option2)
{
       cJSON *root,*fld;
       char *out;
       FILE* fp = Open_File(Pkgs_File, "w+");
       root=cJSON_CreateArray();

       cJSON_AddItemToArray(root,fld=cJSON_CreateObject());
       cJSON_AddStringToObject(fld, "id", "c1");
       cJSON_AddStringToObject(fld, "option", option1);
       cJSON_AddStringToObject(fld, "fid", "1");

       cJSON_AddItemToArray(root,fld=cJSON_CreateObject());
       cJSON_AddStringToObject(fld, "id", "p1");
       cJSON_AddStringToObject(fld, "option", option2);
       cJSON_AddStringToObject(fld, "fid", "2");   
     
       out=cJSON_Print(root);
       fprintf(fp, out);     
       Close_File(fp);

       cJSON_Delete(root);
       free(out);

       out = NULL;

    root = NULL;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值