C/C++解析JSON文件

前面讲了C/C++生成Json文件,那么JSON文件怎么用C/C++解析呢?

相反的步骤罢了  先把JSON文件加载到内存,在从内存中解析

要解析的文件:

{
	"roomNumber":	"B06",
	"peopleCount":	6,
	"roomFreeTabels":	0,
	"roomElemName":	["libero", "rock", "martin", "sky", "bingo", "janny"]
}

 代码demo

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

static int Debug = 1;

using namespace std;

int32_t main(int32_t argc, const char* argv[])
{
	char buf[1024];

	ifstream fin;
	fin.open("cjosn.json", ios_base::in | ios_base::binary);
	
	if (!fin.is_open()) {
		cerr << "file open error!" << endl;
		return -1;
	}

	int index = 0;
	while (!fin.eof()) {
		fin >> buf[index++];
	}
	buf[index] = '\0';

	if (Debug) cout << buf << endl;
	string line(50, '-');
	cout << line << endl;

	fin.close();
	cJSON* root = cJSON_Parse(buf);
	
	cJSON* single = NULL;
	single = cJSON_GetObjectItem(root, "roomNumber");
	printf("roomNumber:%s\n",cJSON_Print(single));
	single = cJSON_GetObjectItem(root, "peopleCount");
	printf("peopleCount:%s\n", cJSON_Print(single));
	single = cJSON_GetObjectItem(root, "roomFreeTabels");
	printf("roomFreeTabels:%s\n", cJSON_Print(single));

	single = cJSON_GetObjectItem(root, "roomElemName");
	printf("roomElemName:");

	int len = cJSON_GetArraySize(single);
	for (int i = 0; i < len; ++i) {
		printf("%s", cJSON_Print(cJSON_GetArrayItem(single, i)));
	}
	cout << endl;

	cJSON_Delete(root);
	
	::system("pause");
	return 0;
}

解析的效果:

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

来一起讨论

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值