linux编程cJSON使用

cJSON

cJSON是一个使用C语言编写的JSON数据解析器,具有超轻便,可移植,单文件的特点,使用MIT开源协议。

cJSON项目托管在Github上,仓库地址如下:

https://github.com/DaveGamble/cJSON

使用

压缩包解压,直接使用里边的cJON.ccJSON.h即可。
链接时还需要加上-lm表示链接math库。

代码

生成JSON对象

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "cJSON.h"

int main(int argc, const char* argv[])
{
    // 创建对象
    cJSON* obj = cJSON_CreateObject();

    // 创建子对象
    cJSON* subObj = cJSON_CreateObject();
    // 添加key-value
    cJSON_AddItemToObject(subObj, "factory", cJSON_CreateString("一汽大众"));
    cJSON_AddItemToObject(subObj, "last", cJSON_CreateNumber(31));
    cJSON_AddItemToObject(subObj, "price", cJSON_CreateNumber(83));
    cJSON_AddItemToObject(subObj, "sell", cJSON_CreateNumber(49));
    cJSON_AddItemToObject(subObj, "sum", cJSON_CreateNumber(80));

    // 创建json数组
    cJSON* array = cJSON_CreateArray();
    // array添加元素
    cJSON_AddItemToArray(array, cJSON_CreateNumber(123));
    cJSON_AddItemToArray(array, cJSON_CreateBool(1));
    cJSON_AddItemToArray(array, cJSON_CreateString("hello, world"));

    // 数组中的对象
    cJSON* subsub = cJSON_CreateObject();
    cJSON_AddItemToObject(subsub, "梅赛德斯奔驰", 
                          cJSON_CreateString("心所向, 持以恒"));
    cJSON_AddItemToArray(array, subsub);

    cJSON_AddItemToObject(subObj, "other", array);

    // obj中添加key - value
    cJSON_AddItemToObject(obj, "奔驰", subObj);

    // 数据格式化
    char* data = cJSON_Print(obj);
    FILE* fp = fopen("car.json", "w");
    fwrite(data, sizeof(char), strlen(data)+1, fp);
    fclose(fp);

    return 0;
}

运行

$ gcc Json_create.c cJSON.c -o jsontest
/usr/bin/ld: /tmp/cc8TufoX.o: in function `print_number':
cJSON.c:(.text+0x794): undefined reference to `floor'
collect2: error: ld returned 1 exit status

这里,要加上-lm

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

运行./jsontest
查看文件

{
	"奔驰":	{
		"factory":	"一汽大众",
		"last":	31,
		"price":	83,
		"sell":	49,
		"sum":	80,
		"other":	[123, true, "hello, world", {
				"梅赛德斯奔驰":	"心所向, 持以恒"
			}]
	}
}

解析JSON

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

int main(int argc, const char* argv[])
{
    if(argc < 2)
    {
        printf("./a.out jsonfile\n");
        return 0;
    }

    // 加载json文件 
    FILE* fp = fopen(argv[1], "r");
    char buf[1024] = {0};
    fread(buf, 1, sizeof(buf), fp);
    cJSON* root = cJSON_Parse(buf);

    cJSON* subobj = cJSON_GetObjectItem(root, "奔驰");
    // 判断对象是否存在
    if( subobj )
    {
        // 获取子对象
        cJSON* factory = cJSON_GetObjectItem(subobj, "factory");
        cJSON* last = cJSON_GetObjectItem(subobj, "last");
        cJSON* price = cJSON_GetObjectItem(subobj, "price");
        cJSON* sell = cJSON_GetObjectItem(subobj, "sell");
        cJSON* sum = cJSON_GetObjectItem(subobj, "sum");
        cJSON* other = cJSON_GetObjectItem(subobj, "other");

        // 打印value值
        printf("奔驰:\n");
        printf("    factory: %s\n", cJSON_Print(factory));
        printf("    last: %s\n", cJSON_Print(last));
        printf("    price: %s\n", cJSON_Print(price));
        printf("    sell: %s\n", cJSON_Print(sell));
        printf("    sum: %s\n", cJSON_Print(sum));

        // 打印数组内容
        printf("    other:\n");
        if(other->type == cJSON_Array)
        {
            for(int i=0; i<cJSON_GetArraySize(other); ++i)
            {
                cJSON* node = cJSON_GetArrayItem(other, i);
                // 判断数据类型
                if(node->type == cJSON_String)
                {
                    printf("        %s  \n", node->valuestring);
                }
                if(node->type == cJSON_Number)
                {
                    printf("        %d\n", node->valueint);
                }
                if(node->type == cJSON_True)
                {
                    printf("        %d\n", node->valueint);
                }
                if(node->type == cJSON_False)
                {
                    printf("        %d\n", node->valueint);
                }
            }
        }
    }

    cJSON_Delete(root);
    fclose(fp);


    return 0;
}

运行

$ gcc parsecar.c cJSON.c -o testParseJson -lm
$ ./testParseJson car.json
奔驰:
    factory: "一汽大众"
    last: 31
    price: 83
    sell: 49
    sum: 80
    other:
        123
        1
        hello, world 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值