linux CJSON使用

最近业务需要跟支付宝进行数据对接,由于对方的数据都是以json格式传送,所以需要对接送格式数据进行解析或组包,cJSON是一种轻量级的数据交换格式。

了解json请参考其官网http://json.org/,cJSON 下载地址http://sourceforge.net/projects/cjson/?source=typ_redirect

文件只有几十k。

test.c 是下载后自带的一个小小的例子,通过这个例子的学习,很快就能掌握json数据结构的构造和解析。

自带例子编译方式如下:

gcc cJSON.c test.c -o jsontest  -lm  

此处记住一定要包含 -lm,因为cJSON.c里面用到了两个数学函数pow floor,否则编译会报错。

一、json库的简单介绍和简单实际应用

cJSON结构体:
typedefstruct cJSON {
structcJSON *next,*prev;
struct cJSON *child;
int type;
char * valuestring;
int valueint;
double valuedouble;
char *string;
}cJSON;


1、cJSON存储的时候是采用链表存储的,其访问方式很像一颗树。每一个节点可以有兄妹节点,通过next/prev指针来查找,它类似双向链表;每个节点也可以有孩子节点,通过child指针来访问,进入下一层。不过,只有节点是对象或数组才可以有孩子节点。
2、type一共有7种取值,分别是:
#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
若是Number类型,则valueint或valuedouble中存储着值,若你期望的是int,则访问valueint,若期望的是double,则访问valuedouble,可以得到值。
若是String类型的,则valuestring中存储着值,可以访问valuestring得到值。
3、string中存放的是这个节点的名字
二、用法举例
自己根据自带的测试程序编写了一个构造和解析json的例子,代码不是很漂亮,主要是为了介绍一下如何使用json库

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


int main (int argc, const char * argv[])
{
    cJSON* pRoot = cJSON_CreateObject();
    cJSON* pArray = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "students_info", pArray);
    char* szOut = cJSON_Print(pRoot);


    cJSON* pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "chenzhongjing");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 28);
    cJSON_AddItemToArray(pArray, pItem);


    pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "fengxuan");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 24);
    cJSON_AddItemToArray(pArray, pItem);


    pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "tuhui");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 22);
    cJSON_AddItemToArray(pArray, pItem);


    char* szJSON = cJSON_Print(pRoot);
    printf("%s\n",szJSON);
    cJSON_Delete(pRoot);


    pRoot = cJSON_Parse(szJSON);
    pArray = cJSON_GetObjectItem(pRoot, "students_info");
    if (NULL == pArray) {
        return -1;
    }


    int iCount = cJSON_GetArraySize(pArray);
    int i = 0;
    for (; i < iCount; ++i) {
        cJSON* pItem = cJSON_GetArrayItem(pArray, i);
        if (NULL == pItem){
            continue;
        }
        char *strName = cJSON_GetObjectItem(pItem, "name")->valuestring;
        char *trSex = cJSON_GetObjectItem(pItem, "sex")->valuestring;
        int iAge = cJSON_GetObjectItem(pItem, "age")->valueint;
        printf("---name=%s\n", strName);
        printf("---sex=%s\n", trSex);
        printf("---age=%d\n", iAge);
    }


    cJSON_Delete(pRoot);
    free(szJSON);
    return 0;
}

gcc -o create cJSON.c create.c -lm
./create


linux CJSON使用