加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

c语言解析json数据

(2015-05-28 19:03:20)
标签:

股票

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

先看json的数据结构
c中没有对象,所以json数据是采用链表存储的
  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;  
typedef struct cJSON {
        struct cJSON *next,*prev;       // 数组 对象数据中用到
        struct cJSON *child;            // 数组 和对象中指向子数组对象或值

        int type;                       // 元素的类型,如是对象还是数组

        char *valuestring;                      // 如果是字符串
        int valueint;                           // 如果是数值
        double valuedouble;                     // 如果类型是cJSON_Number

        char *string;                           // The item's name string, if this item is the child of, or is in the list of subitems of an object.
} 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.  
{
    "name": "Jack (\"Bee\") Nimble", 
    "format": {
        "type":       "rect", 
        "width":      1920, 
        "height":     1080, 
        "interlace":  false, 
        "frame rate": 24
    }
}


那么你可以
1:讲字符串解析成json结构体。
  1. cJSON *root cJSON_Parse(my_json_string);  
cJSON *root = cJSON_Parse(my_json_string);

2:获取某个元素
  1. cJSON *format cJSON_GetObjectItem(root,"format");  
  2. int framerate cJSON_GetObjectItem(format,"frame rate")->valueint;  
cJSON *format = cJSON_GetObjectItem(root,"format");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;

3:讲json结构体转换成字符串
  1. char *rendered=cJSON_Print(root);  
char *rendered=cJSON_Print(root);

4:删除
  1. cJSON_Delete(root);  
cJSON_Delete(root);

5:构建一个json结构体
  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);  

0

阅读 收藏 喜欢 打印举报/Report
前一篇:openwrt 升级
后一篇:ubuntu14.04 lnmp
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有