C語言解析json類型數據


轉自:http://buluzhai.iteye.com/blog/845404   首先感謝作者!!

我使用的是cJSON:http://sourceforge.net/projects/cjson/ 

先看json的數據結構 
c中沒有對象,所以json數據是采用鏈表存儲的 

C代碼如下:

 1 typedef struct cJSON {
 2     struct cJSON *next,*prev;    // 數組 對象數據中用到
 3     struct cJSON *child;        // 數組 和對象中指向子數組對象或值
 4 
 5     int type;            // 元素的類型,如是對象還是數組
 6 
 7     char *valuestring;            // 如果是字符串
 8     int valueint;                // 如果是數值
 9     double valuedouble;            // 如果類型是cJSON_Number
10 
11     char *string;                // The item's name string, if this item is the child of, or is in the list of subitems of an object.
12 } cJSON;

比如你有一個json數據如下:

    

 1 {
 2     "name": "Jack (\"Bee\") Nimble", 
 3     "format": {
 4         "type":       "rect", 
 5         "width":      1920, 
 6         "height":     1080, 
 7         "interlace":  false, 
 8         "frame rate": 24
 9     }
10 }

 

那么你可以 
1:講字符串解析成json結構體。 

C代碼:
    
1 cJSON *root = cJSON_Parse(my_json_string);

 

2:獲取某個元素 

C代碼:
1 cJSON *format = cJSON_GetObjectItem(root,"format");
2 int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;

 

3:講json結構體轉換成字符串

C代碼:
1 char *rendered=cJSON_Print(root);

 

4:刪除 

C代碼:
    
1 cJSON_Delete(root);

 

5:構建一個json結構體 

C代碼:
    
1 cJSON *root,*fmt;
2 root=cJSON_CreateObject();    
3 cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
4 cJSON_AddItemToObject(root, "format", fmt=cJSON_CreateObject());
5 cJSON_AddStringToObject(fmt,"type",        "rect");
6 cJSON_AddNumberToObject(fmt,"width",        1920);
7 cJSON_AddNumberToObject(fmt,"height",        1080);
8 cJSON_AddFalseToObject (fmt,"interlace");
9 cJSON_AddNumberToObject(fmt,"frame rate",    24);

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM