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);
  • 相关阅读:
    php 学习笔记 数组2
    php 学习笔记 数组1
    jQuery prop 全选和全不全
    jquery获取多个checkbox的值异步提交给php
    php 计算多维数组中所有值的总和
    系统状态码原型
    hadoop win10开发环境
    kafka spring整合版本匹配
    mac 安装brew
    hadoop2.8.5 idea2019.1.3插件安装
  • 原文地址:https://www.cnblogs.com/cy568searchx/p/4482734.html
Copyright © 2011-2022 走看看