zoukankan      html  css  js  c++  java
  • cJson 创建 读取

    关于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;
    }

  • 相关阅读:
    【HDOJ5971】Wrestling Match(二分图,并查集)
    【HDOJ5978】To begin or not to begin(概率)
    【HDOJ5979】Convex(三角函数)
    【HDOJ5980】Find Small A(签到)
    【HDOJ5949】Relative atomic mass(签到)
    【HDOJ5948】Thickest Burger(签到)
    【HDOJ6228】Tree(树)
    【HDOJ6227】Rabbits(贪心)
    147.命题逻辑
    146.离散数学
  • 原文地址:https://www.cnblogs.com/cappuccino/p/3207712.html
Copyright © 2011-2022 走看看