通过jsoncpp读取JSON文件

最近需要为C++工程开发一个配置文件功能,经过综合考虑,最后决定使用JSON文件作为配置文件格式。

JSON作为时下最流行的数据交换语言之一,比TXT文件更加简洁明确,比XML更节省存储空间,并且,比数据库更轻巧灵便。在之前的开发经验中,曾经用它来作为配置文件、网络数据传输格式等。JSON由于其简单明晰的数据格式,使得其易于阅读和编辑,也便于机器对其进行解析,因此,最终成为我们的首选。

目前网络上的C++开源JSON库很多,例如RapidJSON、json11、nlohmann、jsoncpp等,想了解更多的同学可参考这位大神的博客:C++中json解析开源库收集,支持json5

我选择的是jsoncpp,不为什么,大概名字更合我心吧哈哈。 

1. jsoncpp库安装

方法1,源码安装 

jsoncpp的开源代码:GitHub-jsoncpp

大家可以自行下载jsoncpp源码,在自己的系统上编译安装,Linux和Windows均可。

方法2,apt-get安装 

在Linux系统上,偷了个懒,直接通过apt-get安装了jsoncpp,命令行如下。

sudo apt-get install libjsoncpp-dev

libjsoncpp.so默认安装路径为/usr/lib/x86_64-linux-gnu/libjsoncpp.so,头文件路径:/usr/include/jsoncpp/json/json.h。如果以上路径不在系统环境变量中,请自行添加。

2. Demo

 jsoncpp在解析JSON文件时最重要的两个结构是Json::Reader和Json::Value。其中,Json::Reader的主要功能是将文件流或字符串解析到Json::Value中,主要使用parse函数;Json::Value可以表示所有支持的类型,如:int、double、string、object、array等。

下面我们通过一个小demo来说明其基本的使用方法。

首先,制作一个JSON文件:

{
	"name": "Grace",
	"sex": "woman",
	"age": 28,
	"marriage": true,
	"education": {
		"university": "USTC",
		"major": "Automation",
		"courses":["Information Technology", "Automatic Control Theory", "Image Processing"]
	}
}

下面是读取以上JSON文件的C++代码:

#include <iostream>
#include <fstream>
#include <string>
#include "jsoncpp/json/json.h"   //头文件在/usr/include/jsoncpp/json/json.h

using namespace std;

int main(int argc, char **argv)
{
	const char *config_file = NULL;
	
	if(argc > 1)
	{
		config_file = (const char*)argv[1];    // Get input json file
	}
	else
	{
		config_file = "config.json";   // If not specified, use the default file name
	}
	
	Json::Reader json_reader;
	Json::Value json_value;
	
	ifstream infile(config_file, ios::binary);
	if(!infile.is_open())
	{
		cout << "Open config file failed!" << endl;
		return -1;
	}
	
	if(json_reader.parse(infile, json_value))
	{	
		string name = json_value["name"].asString();  // 读取字符串型参数
		string sex = json_value["sex"].asString();
		int age = json_value["age"].asInt();   // 读取int型参数
		bool marriage = json_value["marriage"].asBool();   // 读取布尔型参数
		string university = json_value["education"]["university"].asString();  //读取嵌套类型
		string major = json_value["education"]["major"].asString();
		Json::Value courses = json_value["education"]["courses"];  // 读取值为Array的类型
		
		cout << "name = " << name << endl;
		cout << "sex = " << sex << endl;
		cout << "age = " << age << endl;
		cout << "marriage = " << marriage << endl;
		cout << "Education informatin: " << endl;
		cout << "  university: " << university << endl;
		cout << "  major: " << major << endl;
		cout << "  Courses:";
		for(int i = 0; i < courses.size(); i++)
		{
			cout << courses[i].asString();
			if(i != (courses.size() - 1))
			{
				cout << ", ";
			}
			else
			{
				cout << ".";
			}
		}
		cout << endl;

	}
	else
	{
		cout << "Can not parse Json file!";
	}
	
	infile.close();
	
	return 0;
	
}

编译:

g++ -std=c++11 test_jsoncpp.cpp -o test_jsoncpp -ljsoncpp

执行:

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要解析JSON文件,首先需要安装jsoncpp库,可以通过以下命令安装: ``` sudo apt-get install libjsoncpp-dev ``` 安装完毕后,就可以使用jsoncpp库来解析JSON文件了。下面是一个简单的示例程序: ```cpp #include <iostream> #include <fstream> #include <jsoncpp/json/json.h> using namespace std; int main() { ifstream ifs("example.json"); Json::Reader reader; Json::Value root; if (!reader.parse(ifs, root)) { cout << "Failed to parse JSON" << endl; return 1; } string name = root["name"].asString(); int age = root["age"].asInt(); cout << "Name: " << name << endl; cout << "Age: " << age << endl; return 0; } ``` 在这个示例程序中,首先通过ifstream读取example.json文件,然后使用Json::Reader来解析JSON文件解析结果存放在Json::Value对象root中。可以通过root对象来访问JSON中的数据。 在这个示例程序中,我们访问了JSON中的"name"和"age"字段,并将它们打印出来。 需要注意的是,以上示例程序中的JSON文件格式如下: ```json { "name": "John", "age": 30 } ``` 如果JSON文件的格式不正确,解析过程中可能会出现错误。因此,在实际应用中,需要根据实际情况进行错误处理。 ### 回答2: JSONCpp是一个C++的库,用于解析和生成JSON格式的数据。它提供了一组简单的API来读取和修改JSON数据。 使用JSONCpp解析JSON文件的过程包括以下几个步骤: 1. 引入JSONCpp库:在编程环境中,需要将JSONCpp文件引入到项目中。可以从JSONCpp的官方网站上下载并配置库文件。 2. 打开JSON文件:使用JSONCpp库中的`Json::CharReader`来打开JSON文件,将其读取为一个字符串。 3. 解析JSON文件:使用JSONCpp库中的`Json::Value`来解析JSON字符串。可以使用`Json::Reader`的`parse()`方法来将JSON字符串转换为`Json::Value`对象。 4. 提取JSON数据:使用`Json::Value`对象的成员访问运算符`[]`来获取JSON数据。可以使用`isMember()`方法判断指定的成员是否存在,使用`asString()`、`asInt()`等方法获取指定成员的值。 5. 遍历JSON数据:如果JSON数据是一个数组类型,可以使用`size()`方法获取数组的长度,使用`operator[]`来访问数组中的元素。 6. 修改JSON数据:使用`Json::Value`对象的成员访问运算符`[]`来修改JSON数据。可以使用`append()`方法向数组类型的JSON数据中添加元素。 7. 保存JSON文件:使用JSONCpp库中的`Json::StyledWriter`对象将`Json::Value`对象转换为字符串,并将其写入文件中。 总结起来,使用JSONCpp解析JSON文件的过程可以归纳为:引入库文件、打开JSON文件解析JSON文件、提取和操作JSON数据、保存JSON文件。这样就可以实现对JSON文件读取解析操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值