cJSON 使用详解

摘要:
由于C语言中没有字典和字符串数组等直接数据结构,我们需要使用结构定义来处理json。如果有相应的数据结构则更方便,例如在Python Loads中使用json可以方便地将json字符串转换为内置数据结构。下载cjson库文件:sourceforge地址的一个重要概念:在cjson中,json对象可以是json、字符串或数字。。。

由于c语言中,没有直接的字典,字符串数组等数据结构,所以要借助结构体定义,处理json。如果有对应的数据结构就方便一些, 如python中用json.loads(json)就把json字符串转变为内建的数据结构处理起来比较方便。

    cjson库文件下载:

    sourceforge地址

    一个重要概念:

        在cjson中,json对象可以是json,可以是字符串,可以是数字。。。

    cjson数据结构定义:

#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6

typedef struct cJSON {
    struct cJSON *next,*prev;    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

    int type;                    /* The type of the item, as above. cjson结构的类型上面宏定义的7中之一*/

    char *valuestring;            /* The item's string, if type==cJSON_String */
    int valueint;                /* The item's number, if type==cJSON_Number */
    double valuedouble;            /* The item's number, if type==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

        用到的函数,在cJSON.h中都能找到:

/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);//从 给定的json字符串中得到cjson对象
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char  *cJSON_Print(cJSON *item);//从cjson对象中获取有格式的json对象
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char  *cJSON_PrintUnformatted(cJSON *item);//从cjson对象中获取无格式的json对象

/* Delete a cJSON entity and all subentities. */
extern void   cJSON_Delete(cJSON *c);//删除cjson对象,释放链表占用的内存空间

/* Returns the number of items in an array (or object). */
extern int    cJSON_GetArraySize(cJSON *array);//获取cjson对象数组成员的个数
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//根据下标获取cjosn对象数组中的对象
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//根据键获取对应的值(cjson对象)

/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);//获取错误字符串

要解析的json

{
    "semantic": {
        "slots":    {
            "name": "张三"
        }
    },
    "rc":   0,
    "operation":    "CALL",
    "service":  "telephone",
    "text": "打电话给张三"
}

  代码:

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"

void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{
    for(int i=0; i<cJSON_GetArraySize(root); i++)   //遍历最外层json键值对
    {
        cJSON * item = cJSON_GetArrayItem(root, i);        
        if(cJSON_Object == item->type)      //如果对应键的值仍为cJSON_Object就递归调用printJson
            printJson(item);
        else                                //值不为json对象就直接打印出键和值
        {
            printf("%s->", item->string);
            printf("%s
", cJSON_Print(item));
        }
    }
}

int main()
{
    char * jsonStr = "{"semantic":{"slots":{"name":"张三"}}, "rc":0, "operation":"CALL", "service":"telephone", "text":"打电话给张三"}";
    cJSON * root = NULL;
    cJSON * item = NULL;//cjson对象

    root = cJSON_Parse(jsonStr);     
    if (!root) 
    {
        printf("Error before: [%s]
",cJSON_GetErrorPtr());
    }
    else
    {
        printf("%s
", "有格式的方式打印Json:");           
        printf("%s

", cJSON_Print(root));
        printf("%s
", "无格式方式打印json:");
        printf("%s

", cJSON_PrintUnformatted(root));

        printf("%s
", "一步一步的获取name 键值对:");
        printf("%s
", "获取semantic下的cjson对象:");
        item = cJSON_GetObjectItem(root, "semantic");//
        printf("%s
", cJSON_Print(item));
        printf("%s
", "获取slots下的cjson对象");
        item = cJSON_GetObjectItem(item, "slots");
        printf("%s
", cJSON_Print(item));
        printf("%s
", "获取name下的cjson对象");
        item = cJSON_GetObjectItem(item, "name");
        printf("%s
", cJSON_Print(item));

        printf("%s:", item->string);   //看一下cjson对象的结构体中这两个成员的意思
        printf("%s
", item->valuestring);
                        

        printf("
%s
", "打印json所有最内层键值对:");
        printJson(root);
    }
    return 0;    
}

   二、构造json:

    构造 json比较简单,添加json对象即可。参照例子一看大概就明白了。

    主要就是用,cJSON_AddItemToObject函数添加json节点。

xtern cJSON *cJSON_CreateObject(void);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);

extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);

  例子:     要构建的json:

    "semantic": {
        "slots":    {
            "name": "张三"
        }
    },
    "rc":   0,
    "operation":    "CALL",
    "service":  "telephone",
    "text": "打电话给张三"
}

代码:

#include <stdio.h>
#include "cJSON.h"

int main()
{
    cJSON * root =  cJSON_CreateObject();
    cJSON * item =  cJSON_CreateObject();
    cJSON * next =  cJSON_CreateObject();

    cJSON_AddItemToObject(root, "rc", cJSON_CreateNumber(0));//根节点下添加
    cJSON_AddItemToObject(root, "operation", cJSON_CreateString("CALL"));
    cJSON_AddItemToObject(root, "service", cJSON_CreateString("telephone"));
    cJSON_AddItemToObject(root, "text", cJSON_CreateString("打电话给张三"));
    cJSON_AddItemToObject(root, "semantic", item);//root节点下添加semantic节点
    cJSON_AddItemToObject(item, "slots", next);//semantic节点下添加item节点
    cJSON_AddItemToObject(next, "name", cJSON_CreateString("张三"));//添加name节点

    printf("%s
", cJSON_Print(root));

    return 0;
}

免责声明:文章转载自《cJSON 使用详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SPI的学习和ESP8266的SPI通讯测试数据可视化之热力图下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

openssl 学习之从证书中提取RSA公钥N 和 E

原文链接:http://blog.csdn.net/kkxgx/article/details/19850509 通常数字证书包含很多信息,其中N和E值即我们称为的公钥。如何从PEM 或者DER格式的证书中提出证书呢?下面给出代码实现从PEM和DER编码的证书中提出N、E。 [cpp]view plaincopy #include<open...

debezium关于cdc的使用(上)

博文原址:debezium关于cdc的使用(上) 简介 debezium是一个为了捕获数据变更(cdc)的开源的分布式平台。启动并指向数据库,当其他应用对此数据库执行inserts、updates、delete操作时,此应用快速得到响应。debezium是持久化和快速响应的,因此你的应用可以快速响应且不会丢失任意一条事件。debezium记录是数据库表的行...

Stream的流处理--主要用于的是条件的筛选

用优雅的方式写出ArrayList 中的值得条件筛选 主要用到的java8中lambda的表达式 1 public class BaseDemo { 2 public static void main(String[] args) { 3 // 用Stream的方式来筛选list中的值 4 ArrayList...

Spring Security(16)——基于表达式的权限控制

目录 1.1通过表达式控制URL权限 1.2通过表达式控制方法权限 1.2.1使用@PreAuthorize和@PostAuthorize进行访问控制 1.2.2使用@PreFilter和@PostFilter进行过滤 1.3使用hasPermission表达式 Spring Security允许我们在定义URL访问或方法访问所应有的权限时使用Spring...

Java 生成指定时间范围的随机时间、随机中文姓名、随机字符姓名、随机数

解决问题: Java生成指定时间范围的随机时间? Java生成随机中文姓名? Java生成随机字符姓名? Java生成随机数? 代码: import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat...

postman 发送post请求,参数为json

mvc 控制器接收post请求,参数为json PostMan设置 Headers设置key和Value值 key:Content-Type,Value:application/json。 参数设置: 选中Body并进行参数设置,选择raw,格式为json。就酱 控制器代码: //post 请求测试 [HttpPost] //请求方法,...