使用cJSON創建JSON字符串,舉例詳解。(六)

使用cJSON創建JSON字符串

    在Linux下,使用C語言編程,開始JSON字符串的創建。我們還是一步步來,逐漸由簡單到複製。  

1,下載源碼

可以從如下網站來下載:https://sourceforge.net/projects/cjson/ 。

2,包含cJSON的源碼

下載下來,解壓後,從裏面找到兩個文件(cJSON.c、cJSON.h),複製到我們的工程裏面。只需在函數中包含頭文件(#include “cJSON.h”),然後和cJSON.c一起編譯即可使用。 

3,創建一個鍵值對

         首先是一個簡單的鍵值對字符串,要生成的目標如下:

{"firstName":"Brett"}

要進行創建,就是先確定鍵與值,然後轉爲cJSON格式。我們很容易就能明確鍵爲firstName,值爲Brett,可是,使用cJSON怎麼創建呢? 

對於這個簡單的例子,我們需要調用cJSON的五個接口函數就可以實現創建了。(有人不樂意了:都五個函數了,你還說“就可以了”----其實是一法通,百法通,學會了這個創建,其他的創建動作都是非常類似的。)

這五個函數的原型如下:

cJSON*cJSON_CreateObject ();

cJSON*cJSON_CreateString(const char *string);

voidcJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);

voidcJSON_Delete(cJSON *c);

char*cJSON_Print(cJSON *item); 

下面按創建過程來描述一次:

(1)       首先調用cJSON_ CreateObject ()函數,創建一個JSON對象,之後便可向這個對象中添加string或int等內容的數據項了。使用該函數會通過malloc()函數在內存中開闢一個空間,使用完成需要手動釋放。

        cJSON*root=cJSON_CreateObject();

(2)       調用cJSON_CreateString ()函數,由一個字符串生成一個cJSON的數據項。

        cJSON*item=cJSON_CreateString("Brett");

(3)       將上一步生成的數據項與其鍵值("firstName")一起添加到root對象中。

        cJSON_AddItemToObject(root,"firstName",item);

其實到這一步,我們在內存中的cJSON對象就已經構建完成了,後面是展示結果了。

(4)       將cJSON對象的內容解析爲字符串,並展示出來。

        out=cJSON_Print(root);

        printf("out:%s\n",out);

(5)       通過cJSON_Delete(),釋放cJSON_CreateObject ()分配出來的內存空間。

        cJSON_Delete(root);

(6)       釋放cJSON_Print ()分配出來的內存空間。

        free(out); 

         這樣就完成了一次cJSON接口調用,實現了字符串的創建工作。

4,轉換一個結構體 

接下來,我們來個複雜一點的,將一個結構體轉換爲JSON字符串,結構體定義如下:

typedefstruct

{

         char firstName[32];

         char lastName[32];

         char email[64];

         int age;

         float height;

} PERSON;

看起來比一個鍵值對複雜多了,我們又需要學習新的接口函數了嗎?

是的,由於出現了數字,我們需要學習一個新函數:

cJSON *cJSON_CreateNumber(double num);

當然,創建的步驟要更復雜一些,下面我仍然是按創建過程來描述一次: 

(1)還是先調用cJSON_ CreateObject ()函數,創建一個JSON對象root,做爲根(咱們可以把JSON串看成是一顆樹)。使用該函數會通過malloc()函數在內存中開闢一個空間,使用完成需要手動釋放。

        cJSON*root=cJSON_CreateObject();

(2)繼續調用cJSON_ CreateObject ()函數,創建一個JSON對象obj_person,做爲掛載結構體內容的對象。掛載內容之後,這個對象是要掛載到根上的。

        cJSON*obj_person=cJSON_CreateObject();

(3)根據數據生成cJSON格式的數據項,調用cJSON_AddItemToObject()函數掛載到obj_person對象上。這個過程,要多次重複,直到將所有數據都添加上。此時要注意,不同的成員,生成的方法是不一樣的。

        cJSON*item=cJSON_CreateString(person->firstName);

        cJSON_AddItemToObject(obj_person,"firstName",item);

        item=cJSON_CreateString(person->lastName);

        cJSON_AddItemToObject(obj_person,"lastName",item);

        item=cJSON_CreateString(person->email);

        cJSON_AddItemToObject(obj_person,"email",item);

        item=cJSON_CreateNumber(person->age);

        cJSON_AddItemToObject(obj_person,"age",item);

        item=cJSON_CreateNumber(person->height);

        cJSON_AddItemToObject(obj_person,"height",item);

(4)將obj_person對象掛載到根上。

        cJSON_AddItemToObject(root,"person",obj_person);

到這一步,我們在內存中的cJSON對象就已經構建完成了,後面就是展示結果。

(5)將cJSON對象的內容解析爲字符串,並展示出來。

        out=cJSON_Print(root);

        printf("out:%s\n",out);

(6)通過cJSON_Delete(),釋放cJSON_CreateObject ()分配出來的內存空間。這裏說明一下,我們前面調用了2次cJSON_CreateObject (),最後只需要針對root調用一次釋放即可,因爲第二次創建的對象也是掛接在root上的。

        cJSON_Delete(root);

(7)釋放cJSON_Print ()分配出來的內存空間。

        free(out); 

         至此,我們就使用cJSON接口完成了由結構體生成JSON字符串的工作。 

5,創建結構體數組的JSON串   

         最後,我們來個更復雜一些的,來轉換一個數組,並且數組的成員是結構體!我們要生成的目標如下:

{

"people":[

{"firstName":"z","lastName":"Jason","email":"[email protected]","height":1.67},

{"lastName":"jadena","email":"[email protected]","age":8,"height":1.17},

{"email":"[email protected]","firstName":"z","lastName":"Juliet","age":36,"height":1.55}

]

此時,我們又需要學習新的接口了,一個是創建數組,一個是取數組成員,函數原型如下:

cJSON*cJSON_CreateArray(void);

void   cJSON_AddItemToArray(cJSON *array, cJSON*item); 

由於前面已經實現了單個結構體的轉換,這裏我們重點關注下數組的相關調用。 

(1)還是先調用cJSON_ CreateObject ()函數,創建一個JSON對象root,做爲根。

(2)調用cJSON_CreateArray ()函數,創建一個JSON數組對象,準備掛載多個結構體對象。掛載內容之後,這個數組對象是要掛載到根上的。

        cJSON*array_person=cJSON_CreateArray();

(3)生成一個結構體對象,並相應添加數據,然後調用cJSON_AddItemToArray()函數掛載到數組對象上。這個過程,要多次重複,直到將所有結構體對象都添加上。

        cJSON_AddItemToArray(array_person,obj_person);

(4)將數組對象掛載到根上。

        cJSON_AddItemToObject(root,"people",array_person);

到這一步,我們在內存中的cJSON對象就已經構建完成了。

(5)將cJSON對象的內容解析爲字符串,並展示出來。

(6)通過cJSON_Delete(),釋放cJSON_CreateObject ()分配出來的內存空間。

(7)釋放cJSON_Print ()分配出來的內存空間。

         這樣,我們就使用cJSON接口完成了將結構體數組轉換成JSON字符串的工作。

詳細代碼見後文附帶例程。         

說明:

本文所附帶例程,實現了結構體數組生成JSON字符串,只是一個學習之作,對於初學cJSON的同學,可以有些借鑑參考的作用。 

附帶例程: 

[cpp] view plain copy

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <sys/types.h>  
  4. #include <stdlib.h>  
  5. #include <unistd.h>  
  6.   
  7. #include "cJSON.h"  
  8.   
  9. typedef struct  
  10. {  
  11.     int id;  
  12.     char firstName[32];  
  13.     char lastName[32];  
  14.     char email[64];  
  15.     int age;  
  16.     float height;  
  17. }people;  
  18.   
  19. void dofile(char *filename);/* Read a file, parse, render back, etc. */  
  20.   
  21. int main(int argc, char **argv)  
  22. {  
  23.   
  24.     dofile("json_str4.txt");  
  25.   
  26.     return 0;  
  27. }  
  28.   
  29.   
  30. //create a key-value pair  
  31. int str_to_cJSON(char *json_string, char *str_val)  
  32. {  
  33.     char * out=NULL;  
  34.     cJSON *root=cJSON_CreateObject();  
  35.     if (!root)  
  36.     {  
  37.         printf("Error before: [%s]\n",cJSON_GetErrorPtr());  
  38.         return -1;  
  39.     }  
  40.     else  
  41.     {  
  42.         cJSON *item=cJSON_CreateString("Brett");  
  43.         cJSON_AddItemToObject(root,"firstName",item);  
  44.   
  45.         out=cJSON_Print(root);  
  46.         printf("out2:%s\n",out);  
  47.   
  48.         cJSON_Delete(root);  
  49.         if(out!=NULL)  
  50.         {  
  51.             free(out);  
  52.         }  
  53.     }  
  54.     return 0;  
  55. }  
  56.   
  57. //create a object from struct  
  58. int struct_to_cJSON(char *json_string, people *person)  
  59. {  
  60.   
  61.     if((json_string==NULL) || (person==NULL))  
  62.     {  
  63.         printf("%s: input is invalid",__func__);  
  64.     }  
  65.   
  66.     char * out=NULL;  
  67.     cJSON *root=cJSON_CreateObject();  
  68.   
  69.     if (!root)  
  70.     {  
  71.         printf("Error before: [%s]\n",cJSON_GetErrorPtr());  
  72.         return -1;  
  73.     }  
  74.     else  
  75.     {  
  76.         cJSON *obj_person=cJSON_CreateObject();  
  77.   
  78.         cJSON *item=cJSON_CreateString(person->firstName);  
  79.         cJSON_AddItemToObject(obj_person,"firstName",item);  
  80.   
  81.         item=cJSON_CreateString(person->lastName);  
  82.         cJSON_AddItemToObject(obj_person,"lastName",item);  
  83.   
  84.         item=cJSON_CreateString(person->email);  
  85.         cJSON_AddItemToObject(obj_person,"email",item);  
  86.   
  87.         item=cJSON_CreateNumber(person->age);  
  88.         cJSON_AddItemToObject(obj_person,"age",item);  
  89.   
  90.         item=cJSON_CreateNumber(person->height);  
  91.         cJSON_AddItemToObject(obj_person,"height",item);  
  92.   
  93.         cJSON_AddItemToObject(root,"person",obj_person);  
  94.   
  95.         out=cJSON_Print(root);  
  96.         printf("out2:%s\n",out);  
  97.   
  98.         cJSON_Delete(root);  
  99.         if(out!=NULL)  
  100.         {  
  101.             memcpy(json_string,out,strlen(out));  
  102.             free(out);  
  103.         }  
  104.     }  
  105.   
  106.     return 0;  
  107. }  
  108.   
  109.   
  110. //a struct array to CJSON  
  111. int struct_array_to_cJSON(char *text, people worker[])  
  112. {  
  113.     cJSON *json,*arrayItem,*item,*object;  
  114.     int i;  
  115.   
  116.     for(i=0;i<3;i++)  
  117.     {  
  118.         printf("i=%d, firstName=%s,lastName=%s,email=%s,age=%d,height=%f\n",  
  119.                 i,  
  120.                 worker[i].firstName,  
  121.                 worker[i].lastName,  
  122.                 worker[i].email,  
  123.                 worker[i].age,  
  124.                 worker[i].height);  
  125.     }  
  126.   
  127.     if((text==NULL) || (worker==NULL))  
  128.     {  
  129.         printf("%s: input is invalid",__func__);  
  130.     }  
  131.   
  132.     char * out=NULL;  
  133.     cJSON *root=cJSON_CreateObject();  
  134.   
  135.     if (!root)  
  136.     {  
  137.         printf("Error before: [%s]\n",cJSON_GetErrorPtr());  
  138.         return -1;  
  139.     }  
  140.     else  
  141.     {  
  142.         cJSON *array_person=cJSON_CreateArray();  
  143.   
  144.         for(i=0;i<3;i++)  
  145.         {  
  146.             cJSON *obj_person=cJSON_CreateObject();  
  147.   
  148.             cJSON *item=cJSON_CreateString(worker[i].firstName);  
  149.             cJSON_AddItemToObject(obj_person,"firstName",item);  
  150.   
  151.             item=cJSON_CreateString(worker[i].lastName);  
  152.             cJSON_AddItemToObject(obj_person,"lastName",item);  
  153.   
  154.             item=cJSON_CreateString(worker[i].email);  
  155.             cJSON_AddItemToObject(obj_person,"email",item);  
  156.   
  157.             item=cJSON_CreateNumber(worker[i].age);  
  158.             cJSON_AddItemToObject(obj_person,"age",item);  
  159.   
  160.             item=cJSON_CreateNumber(worker[i].height);  
  161.             cJSON_AddItemToObject(obj_person,"height",item);  
  162.   
  163.             cJSON_AddItemToArray(array_person,obj_person);  
  164.         }  
  165.   
  166.         cJSON_AddItemToObject(root,"people",array_person);  
  167.   
  168.         out=cJSON_Print(root);  
  169.         printf("out:%s\n",out);  
  170.   
  171.         cJSON_Delete(root);  
  172.         if(out!=NULL)  
  173.         {  
  174.             memcpy(text,out,strlen(out));  
  175.             free(out);  
  176.         }  
  177.     }  
  178.   
  179.     return 0;  
  180. }  
  181.   
  182. // create CJSON, write file  
  183. void dofile(char *filename)  
  184. {  
  185.     FILE *f;  
  186.     int len;  
  187.     char data[1024];  
  188.       
  189.     f=fopen(filename,"wb");  
  190.     fseek(f,0,SEEK_END);  
  191.     len=ftell(f);  
  192.     fseek(f,0,SEEK_SET);  
  193.       
  194.     printf("read file %s complete, len=%d.\n",filename,len);  
  195.   
  196. //  char str_name[40];  
  197. //  int ret = str_to_cJSON(data, str_name);  
  198.   
  199.     people worker[3]={  
  200.             {0,"zhong","Jason","[email protected]",0,1.67},  
  201.             {1,"","jadena","[email protected]",8,1.17},  
  202.             {2,"zhu","Juliet","[email protected]",36,1.55}  
  203.     };  
  204. //  struct_to_cJSON(data, &worker[1]);  
  205.     struct_array_to_cJSON(data, worker);  
  206.   
  207.     fwrite(data,1,strlen(data),f);  
  208.     fclose(f);  
  209.   

 

 

 

http://blog.csdn.net/lintax/article/details/51549345

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章