网络传输中,数据交互也需要一些自定义协议,其实json就是最好用之一。

使用cjson进行json字符串的构造,以及对其进行对应解析的测试代码。

1:背景介绍

JSNON作为一种轻量级的数据交互格式,易于阅读和编写,易于解析和生成。

日常开发中对json的使用次数也越来越多。

我常用的就是使用cjon以及jsoncpp对数据进行构造以及解析。

cjson因为直接包含一个头文件和.c文件就可以使用,特别方便,这里整理一些使用cjson进行构造与解析的实例,做代码备份。

2:测试代码

2.1:构造json格式的数据,返回json字符串

/*********************
{
	"name":	"test",
	"age":	80,
	"languages":	["C++", "Java"],
	"phone":	{
		"number":	"1867216i144",
		"type":	"home"
	},
	"languages":	[{
			"name":	"Linux kernel development",
			"price":	"7.7"
		}, {
			"name":	"Linux server development",
			"price":	"8.0"
		}],
	"vip":	true,
	"address":	""
}
*********************/

char * make_json_str()
 {
 	// 创建json对象
    cJSON *root = cJSON_CreateObject();
    // 添加键值对
    cJSON_AddItemToObject(root, "name", cJSON_CreateString("test"));
    cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(80));
    // 创建json数组
    cJSON *languages = cJSON_CreateArray();
    cJSON_AddItemToArray(languages, cJSON_CreateString("C++"));
    cJSON_AddItemToArray(languages, cJSON_CreateString("Java"));
    cJSON_AddItemToObject(root, "languages", languages);

    cJSON *phone = cJSON_CreateObject();
    cJSON_AddItemToObject(phone, "number", cJSON_CreateString("1867216i144"));
    cJSON_AddItemToObject(phone, "type", cJSON_CreateString("home"));
    cJSON_AddItemToObject(root, "phone", phone);

    cJSON *book0 = cJSON_CreateObject();
    cJSON_AddItemToObject(book0, "name", cJSON_CreateString("Linux kernel development"));
    cJSON_AddItemToObject(book0, "price", cJSON_CreateNumber(7.7));
    cJSON *book1 = cJSON_CreateObject();
    cJSON_AddItemToObject(book1, "name", cJSON_CreateString("Linux server development"));
    cJSON_AddItemToObject(book1, "price", cJSON_CreateNumber(8.0));
    // 创建json数组
    cJSON *books = cJSON_CreateArray();
    cJSON_AddItemToArray(books, book0);
    cJSON_AddItemToArray(books, book1);
    cJSON_AddItemToObject(root, "books", books);

    cJSON_AddItemToObject(root, "vip", cJSON_CreateBool(1));
    cJSON_AddItemToObject(root, "address", cJSON_CreateString("")); // NULL值的问题

    //格式化json对象 并返回
    char *jsonstr = cJSON_Print(root);
    //注意释放 内部会释放其子节点的
    cJSON_Delete(root);

    printf("make json str is [%lu][%s] \n", strlen(jsonstr), jsonstr);
    return jsonstr;
 }

2.2:json字符串对应的解析

void printCJson(cJSON *root);
int parse_json_str(const char * jsonstr)
{
	if(jsonstr == NULL)
	{
		printf("parse json error: jsonstr is null \n");
		return -1;
	}
	cJSON *root = cJSON_Parse(jsonstr);
	if(root == NULL)
	{
		printf("parse json error: cJSON_Parse error \n");
		return -1;
	}
	//获取对应的字段并进行打印
	printCJson(root);
	cJSON_Delete(root);
    return 0;
}

void printCJson(cJSON *root)
{
	//获取到各个子对象
	cJSON *name = cJSON_GetObjectItem(root, "name");
    cJSON *age = cJSON_GetObjectItem(root, "age");
    cJSON *languages = cJSON_GetObjectItem(root, "languages");
    cJSON *phone = cJSON_GetObjectItem(root, "phone");
    cJSON *books = cJSON_GetObjectItem(root, "books");
    cJSON *vip = cJSON_GetObjectItem(root, "vip");
    cJSON *address = cJSON_GetObjectItem(root, "address");

    printf(" name: %s\n", name->valuestring);
    printf(" age: %d\n", age->valueint);
    printf(" languages: ");
    for (int i = 0; i < cJSON_GetArraySize(languages); i++)
    {
        cJSON *lang = cJSON_GetArrayItem(languages, i);
        if (i != 0)
        {
            printf(", ");
        }
        printf("%s", lang->valuestring);
    }
    printf("\n");

    cJSON *number = cJSON_GetObjectItem(phone, "number");
    cJSON *type = cJSON_GetObjectItem(phone, "type");
    printf(" phone number: %s, type: %s\n", number->valuestring, type->valuestring);

    for (int i = 0; i < cJSON_GetArraySize(books); i++)
    {
        cJSON *book = cJSON_GetArrayItem(books, i);
        cJSON *name = cJSON_GetObjectItem(book, "name");
        cJSON *price = cJSON_GetObjectItem(book, "price");
        printf(" book name: %s, price: %lf\n", name->valuestring, price->valuedouble);
    }

    printf(" vip: %d\n", vip->valueint);
    if (address && !cJSON_IsNull(address))
    {
        printf(" address: %s\n", address->valuestring);
    }
    else
    {
        printf(" address is null\n");
    }
}

2.3:测试调用主函数

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"   //需要包含cjson的头文件 以及编译时要编译对应的cjson.c一起

int main()
{
	//构造json字符串  内部会对json字符串申请内存 要释放
	char * strjson = make_json_str();
	//解析构造的json字符串 打印对应的字段
	parse_json_str(strjson);
	free(strjson);
	return 0;
}

3:执行结果

make json str is [286][{
	"name":	"test",
	"age":	80,
	"languages":	["C++", "Java"],
	"phone":	{
		"number":	"1867216i144",
		"type":	"home"
	},
	"books":	[{
			"name":	"Linux kernel development",
			"price":	7.7
		}, {
			"name":	"Linux server development",
			"price":	8
		}],
	"vip":	true,
	"address":	""
}] 
 name: test
 age: 80
 languages: C++, Java
 phone number: 1867216i144, type: home
 book name: Linux kernel development, price: 7.700000
 book name: Linux server development, price: 8.000000
 vip: 1
 address: 

我开始试着积累一些常用代码:自己代码库中备用

我的知识储备更多来自这里,推荐你了解:Linux,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK等技术内容,立即学习

GitHub 加速计划 / cj / cJSON
10.45 K
3.16 K
下载
Ultralightweight JSON parser in ANSI C
最近提交(Master分支:2 个月前 )
424ce4ce This reverts commit 5b502cdbfb21fbe5f6cf9ffbd2b96e4281a741e6. Related to #860 4 个月前
32497300 - 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐