linux下用cjson實現對資料索引值對的封裝儲存

來源:互聯網
上載者:User

標籤:linux


首先需要下載封裝好的cjson包包括 cjson.h cjson.c

為方便大家我已上傳

如下

http://download.csdn.net/detail/wuheshi/8353075

編程時加入標頭檔cjson.h 就可以調用cjson.c裡面的函數

打包json資料和解析json資料例子如下:

簡單編碼執行個體如下


#include "../../include/myhead.h"
#include "../../include/cJSON.h"

/*對json資料的解析取出其中的有用資訊*/
int undo_cjson_pack(char text[],int id,int ctlcmd)  
{  
    cJSON *json, *json_value;  
    // 解析資料包  
    json = cJSON_Parse(text);  
    if (!json)  
    {  
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());      //判斷是否是json資料
    }  
    else  
    {  
        // 解析ID值  
        json_value = cJSON_GetObjectItem( json , "ID");  
        if( json_value->type == cJSON_Number )  
        {  
            // 從valueint中獲得結果  
            printf("value:%d\r\n",json_value->valueint);
            id = json_value->valueint  ;
        }  
        // 解析 控制量
        json_value = cJSON_GetObjectItem( json , "ctl_cmd");  
        if( json_value->type == cJSON_Number )  
        {  
            // valuestring中獲得結果  
            printf("cmd:%d\r\n",json_value->valueint);  
             ctlcmd =json_value->valueint;
            //  printf("%s\n",cmd);     
        }  
        // 釋放記憶體空間  
        cJSON_Delete(json);  
    }  
    return 0;  
}  

/*打包資料鍵值對成json格式再傳給字串*/
char * do_cjson_pack(int idnum,char *str)  
{  
    // 建立JSON Object  
    cJSON *root = cJSON_CreateObject();  
    // 加入節點(鍵值對),節點名稱為ID,節點值為123.4  
    cJSON_AddNumberToObject(root,"ID",idnum);
    cJSON_AddStringToObject(root,"ctl_cmd",str);
    // 列印JSON資料包  
    char *out = cJSON_Print(root);  
    printf("%s\n",out);  
    // 釋放記憶體  
    cJSON_Delete(root);       
    return out;  
}  


/*
int main()
{
      char text[] = "{\"ctl_cmd\":\6,\"ID\":1}";  
      char *putout = NULL;
      int cmd_str = 1;
      int num = 9;
      
      putout = do_cjson_pack(num,cmd_str) ;
      undo_cjson_pack(text);  
    
      printf("%s\n",putout);
      free(putout);
      return 0;

}

*/


程式有點小改動,運行時有錯誤的話 可能資料格式有點問題,這裡解釋作用

linux下用cjson實現對資料索引值對的封裝儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.