C/C++生成JSON文件

前面我们介绍了 JSON文件是个什么样子,那么在编程中我们怎么用呢?

C/C++怎么生成JSON文件格式呢?

 

这里我们就是用一个开源库 cJSON(方法多种多样也可以用其他的库)来生成一个json文件。

如下是我们要生成的一个json文件

{
	"roomNumber" : "B06",          // 宿舍编号
	"peopleCount" : 6,				// 宿舍人数
    "roomFreeTabels" : 0,			// 宿舍空闲床位
    "roomElemName" : [				// 宿舍人的姓名
    	"libero", 
    	"rock",
    	"martin",
    	"sky",
    	"bingo",
    	"janny"
    ]
}

代码Demo

#include <iostream>
#include <Windows.h>
#include <fstream>
#include "cJSON.h"

using namespace std;

#define _CRT_SECURE_NO_WARNINGS
#define OPEN_MAX_TIMES 5

int main(int argc, const char* argv[])
{
	cJSON* root = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "roomNumber", cJSON_CreateString("B06"));
	cJSON_AddItemToObject(root, "peopleCount", cJSON_CreateNumber(6));
	cJSON_AddItemToObject(root, "roomFreeTabels", cJSON_CreateNumber(0));

	// 姓名数组 这里可以用循环代替 这样一个个写太low了
	// 但是为了让大家更清晰的看还是一个个写
	cJSON* array = cJSON_CreateArray();
	cJSON_AddItemToArray(array, cJSON_CreateString("libero"));
	cJSON_AddItemToArray(array, cJSON_CreateString("rock"));
	cJSON_AddItemToArray(array, cJSON_CreateString("martin"));
	cJSON_AddItemToArray(array, cJSON_CreateString("sky"));
	cJSON_AddItemToArray(array, cJSON_CreateString("bingo"));
	cJSON_AddItemToArray(array, cJSON_CreateString("janny"));

	// 把数组加紧 大的对象中
	cJSON_AddItemToObject(root, "roomElemName", array);

	// 写道文件中去
	char* buf = cJSON_Print(root);

	ofstream fout;
	fout.open("cjosn.json", ios_base::out | ios_base::binary);  // 二进制的写
	int count = 0;
	while (!fout.is_open() && count < OPEN_MAX_TIMES) {
		cerr << "open file error.has " << OPEN_MAX_TIMES - (++count) 
			<< "times retry" << endl;
	}

	do{
		if (count == 5) {
			cerr << "file open error total" << endl;
			break;
		}
		fout << buf << flush;
		fout.close();
	} while (0);

	cJSON_Delete(root);

	system("pause");
	return 0;
}

生成的文件:

更多的关于数据库学习我会在下面的文章中陆续的分享,也可以关注‘奇牛学院’

来一起讨论

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/107374571