C++ 使用jsoncpp解析json文件

今天复习一下jsoncpp解析库的用法

1.Github搜jsoncpp下载工程源码

Github传送门
下载工程源码:
在这里插入图片描述

2.解压得到需要使用的两个目录include和src

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

3. 创建新测试工程:

在这里插入图片描述

4.解决方案目录下创建新目录json,存储上文拿到的json文件:

在这里插入图片描述
在这里插入图片描述

5.测试工程添加筛选器,并且添加进去得到的jsoncpp文件:

在这里插入图片描述

6.工程属性,附加包含两个目录:

在这里插入图片描述

在这里插入图片描述

7.添加解析类 JsoncppAssistant

#pragma once
#include "json.h"
#include <vector>
#include <mutex>
using namespace std;


struct Score
{
	string subject;
	float score;
	bool bChecked;
	Score(const string& nm, float fS,bool bV = true)
		:subject(nm),
		score(fS),
		bChecked(bV)
	{
		bChecked = true;
	}
};
struct Student
{
	string name;
	vector<Score> arr;
};

//两个全局互斥锁保证多线程调用Read()、Write()方法线程安全
extern std::mutex g_read_mutex;
extern std::mutex g_write_mutex;
class JsoncppAssistant
{
private:
	JsoncppAssistant() = default;
	~JsoncppAssistant() = default;
	JsoncppAssistant(const JsoncppAssistant& src) = delete;
	JsoncppAssistant& operator=(const JsoncppAssistant& src) = delete;
	static JsoncppAssistant* instance;
	static std::mutex m_mutex;
public:
	/*
	双重检查锁定(double-checked locking)模式和互斥锁 m_mutex
	确保在多线程环境下只创建一个 JsoncppAssistant 
	*/
	static JsoncppAssistant* GetInstance()
	{
		if (instance == nullptr)
		{
			//锁定互斥量
			std::lock_guard<std::mutex> lock(m_mutex);
			if (instance == nullptr)
			{
				instance = new JsoncppAssistant();
			}
		}
		return instance;
	}
	bool Read(vector<Student>& arr, string path = "");
	bool Write(const vector<Student>& arr);
};

extern JsoncppAssistant* GetJscppMgr();



#include "JsoncppAssistant.h"
#include <ostream>
#include <fstream>


std::mutex g_read_mutex;
std::mutex g_write_mutex;
JsoncppAssistant* JsoncppAssistant::instance = nullptr;
std::mutex JsoncppAssistant::m_mutex;


JsoncppAssistant* GetJscppMgr()
{
	return JsoncppAssistant::GetInstance();
}

bool JsoncppAssistant::Read(vector<Student>& arr, string path)
{
	std::lock_guard<std::mutex> lock(g_read_mutex);
	arr.clear();

	Json::Reader reader;
	Json::Value root;

	ifstream ifs;
	ifs.open("test.json");
	if (!ifs.is_open())
	{
		return false;
	}

	if (!reader.parse(ifs, root))
	{
		return false;
	}
	if (root["data"].isNull()) return false;

	int nSize = root["data"].size();
	for (int i = 0; i < nSize; i++)
	{
		Student stu;
		stu.name = root["data"][i]["name"].asString();
		if (!root["data"][i]["Score"].isNull())
		{
			int nSz2 = root["data"][i]["Score"].size();
			stu.arr.reserve(nSz2);
			for (int j = 0; j < nSz2; j++)
			{
				stu.arr.emplace_back(Score(root["data"][i]["Score"][j]["subject"].asString(),
					root["data"][i]["Score"][j]["score"].asFloat(),
					root["data"][i]["Score"][j]["bChecked"].asBool()));
			}
		}
		arr.push_back(stu);
	}
	return true;
}


bool JsoncppAssistant::Write(const vector<Student>& arr)
{
	std::lock_guard<std::mutex> lock(g_write_mutex);
	if (arr.empty()) return false;

	Json::Value root;

	for (const auto& it : arr)
	{
		Json::Value JsStu;
		JsStu["name"] = it.name;
		for (const auto& it2 : it.arr)
		{
			Json::Value JsScore;
			JsScore["subject"] = it2.subject;
			JsScore["score"] = it2.score;
			JsScore["bChecked"] = it2.bChecked;
			JsStu["Score"].append(JsScore);
		}
		root["data"].append(JsStu);
	}

	Json::StreamWriterBuilder writerBuilder;
	std::string json_file = Json::writeString(writerBuilder, root);
	ofstream ofs("test.json", std::ios::out | std::ios::trunc);
	if (!ofs.is_open())
	{
		return false;
	}
	ofs << json_file;
	ofs.close();
	return true;
}

8.测试看看:

8.1写文件

void Write()
{
    vector<Student> arr;

    Student aaa;
    aaa.name = "aaa";
    aaa.arr.push_back(Score("c", 60.5));
    aaa.arr.push_back(Score("cpp", 88.5));
    aaa.arr.push_back(Score("python", 99.5));
    arr.push_back(aaa);
    Student bbb;
    bbb.name = "bbb";
    bbb.arr.push_back(Score("c", 77.5));
    bbb.arr.push_back(Score("cpp", 67));
    bbb.arr.push_back(Score("python", 95));
    arr.push_back(bbb);
    Student ccc;
    ccc.name = "ccc";
    ccc.arr.push_back(Score("c", 85));
    ccc.arr.push_back(Score("cpp", 76.5));
    ccc.arr.push_back(Score("python", 69.5));
    arr.push_back(ccc);

    GetJscppMgr()->Write(arr);
}

在这里插入图片描述

在这里插入图片描述

8.2读文件:

bool JsoncppAssistant::Read(vector<Student>& arr, string path)
{
	arr.clear();

	Json::Reader reader;
	Json::Value root;

	ifstream ifs;
	ifs.open("test.json");
	if (!ifs.is_open())
	{
		return false;
	}

	if (!reader.parse(ifs, root))
	{
		return false;
	}
	if (root["data"].isNull()) return false;

	int nSize = root["data"].size();
	for (int i = 0; i < nSize; i++)
	{
		Student stu;
		stu.name = root["data"][i]["name"].asString();
		if (!root["data"][i]["Score"].isNull())
		{
			int nSz2 = root["data"][i]["Score"].size();
			stu.arr.reserve(nSz2);
			for (int j = 0; j < nSz2; j++)
			{
				stu.arr.push_back(Score(root["data"][i]["Score"][j]["subject"].asString(),
					root["data"][i]["Score"][j]["score"].asFloat(),
					root["data"][i]["Score"][j]["bChecked"].asBool()));
			}
		}
		arr.push_back(stu);
	}
	return true;
}

在这里插入图片描述

  • 0
    点赞
  • 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、付费专栏及课程。

余额充值