zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    ffplay.c函数结构简单分析(绘图)
    SNMP安全配置的两种方法(也可同一时候兼顾配置两种方法)
    LINKs: Xamarin.Forms + Prism
    Linux目录详解
    搜狗输入法 for Linux v2.2.0.0108
    centos 查看IP
    CentOS安装系统时硬盘分区建议
    CentOS 7 各个版本的区别
    VMware安装Centos7超详细过程(图文)
    Centos7从零开始】Centos 下硬盘分区的最佳方案
  • 原文地址:https://www.cnblogs.com/cy568searchx/p/4482734.html
Copyright © 2011-2022 走看看