c++ 使用rapidjson读写json文件示例

1、rapidjson简介

rapidjson 是腾讯开发的一个 C++ 的 JSON 解析和生成库,它是一个完全以C++头文件方式提供的库,它的目标是快速和高效操作JSON文件。

Github地址如下:

github.com

2. JSON文件

{
    "Title": "Introducing Modbus Protocol", 
    "Company": "Modicon inc.", 
    "Keywords": "Modbus json", 
    "TotalFunc": 5, 
    "FuncCode": [
        "Read Coil Status", 
        "Read Input Status", 
        "Read Holding Registers", 
        "Read Input Registers", 
        "Force Single Coil"
    ], 
    "ErrorCheck": {
        "Methods": [
            "LRC", 
            "CRC"
        ]
    }, 
    "Appendix": {
        "ApplicationNotes": "The maximum length of the entire message must not exceed 256 bytes."
    }
}

3. 生成JSON文件

//生成JSON
void MakeJson(std::string& str_json)
{
	rapidjson::StringBuffer strBuf;
	rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);

	writer.StartObject();

	writer.Key("Title");
	writer.String("Introducing Modbus Protocol");
	writer.Key("Company");
	writer.String("Modicon inc.");
	writer.Key("Keywords");
	writer.String("Modbus json");
	writer.Key("TotalFunc");
	writer.Int(5);

	writer.Key("FuncCode");            
	writer.StartArray();
	writer.String("Read Coil Status");
	writer.String("Read Input Status");
	writer.String("Read Holding Registers");
	writer.String("Read Input Registers");
	writer.String("Force Single Coil");              
	writer.EndArray();      

	writer.Key("ErrorCheck");
	writer.StartObject();
	writer.Key("Methods");
	writer.StartArray();
	writer.String("LRC");
	writer.String("CRC");
	writer.EndArray();
	writer.EndObject();

	writer.Key("Appendix");
	writer.StartObject();
	  writer.Key("ApplicationNotes");
	  writer.String("The maximum length of the entire message must not exceed 256 bytes.");
	writer.EndObject();

	writer.EndObject();

	str_json = strBuf.GetString();

	return;
}

4. 解析JSON文件

//解析JSON
void ParseJson(std::string str_json)
{
	if (str_json.empty())
		return;

	rapidjson::Document dom;
	if (!dom.Parse(str_json.c_str()).HasParseError())
	{
		//解析常规Key-Value
		if (dom.HasMember(TEXT("Title")) && dom[TEXT("Title")].IsString())
		{
			std::cout << "【Title】 = " << dom[TEXT("Title")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("Company")) && dom[TEXT("Company")].IsString())
		{
			std::cout << "【Company】 = " << dom[TEXT("Company")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("Keywords")) && dom[TEXT("Keywords")].IsString())
		{
			std::cout << "【Keywords】 = " << dom[TEXT("Keywords")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("TotalFunc")) && dom[TEXT("TotalFunc")].IsInt())
		{
			std::cout << "【TotalFunc】 = " << dom[TEXT("TotalFunc")].GetInt() << std::endl;
		}

		//解析数组
		if (dom.HasMember(TEXT("FuncCode")) && dom[TEXT("FuncCode")].IsArray())
		{
			const rapidjson::Value& arrFuncCode = dom[TEXT("FuncCode")];
			int iCount = arrFuncCode.Size();
			for (int ii = 0; ii < iCount;++ii)
			{
				if (arrFuncCode[ii].IsString())
				{
					std::cout << "  【FuncCode】 = " << arrFuncCode[ii].GetString() << std::endl;
				}
			}
		}

		//解析对象
		if (dom.HasMember(TEXT("ErrorCheck")) && dom[TEXT("ErrorCheck")].IsObject())
		{
			const rapidjson::Value& objErrorCheck = dom[TEXT("ErrorCheck")];

			if (objErrorCheck.HasMember(TEXT("Methods")) && objErrorCheck[TEXT("Methods")].IsArray())
			{
				const rapidjson::Value& arrMethods = objErrorCheck[TEXT("Methods")];
				int iCount = arrMethods.Size();
				for (int ii = 0; ii < iCount; ++ii)
				{
					if (arrMethods[ii].IsString())
					{
						std::cout << "  【Methods】 =" << arrMethods[ii].GetString() << std::endl;
					}
				}
			}
		}

		if (dom.HasMember(TEXT("Appendix")) && dom[TEXT("Appendix")].IsObject())
		{
			const rapidjson::Value& objAppendix = dom[TEXT("Appendix")];

			if (objAppendix.HasMember(TEXT("ApplicationNotes")) && objAppendix[TEXT("ApplicationNotes")].IsString())
			{
				std::cout << "【Appendix】 = " << objAppendix[TEXT("ApplicationNotes")].GetString() << std::endl;
			}
		}
	}
}

5.简单示例

#include <string>
#include <iostream>

#include "rapidjson/writer.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"

//生成JSON
void MakeJson(std::string& str_json)
{
	rapidjson::StringBuffer strBuf;
	rapidjson::Writer<rapidjson::StringBuffer> writer(strBuf);

	writer.StartObject();

	writer.Key("Title");
	writer.String("Introducing Modbus Protocol");
	writer.Key("Company");
	writer.String("Modicon inc.");
	writer.Key("Keywords");
	writer.String("Modbus json");
	writer.Key("TotalFunc");
	writer.Int(5);

	writer.Key("FuncCode");            
	writer.StartArray();
	writer.String("Read Coil Status");
	writer.String("Read Input Status");
	writer.String("Read Holding Registers");
	writer.String("Read Input Registers");
	writer.String("Force Single Coil");              
	writer.EndArray();      

	writer.Key("ErrorCheck");
	writer.StartObject();
	writer.Key("Methods");
	writer.StartArray();
	writer.String("LRC");
	writer.String("CRC");
	writer.EndArray();
	writer.EndObject();

	writer.Key("Appendix");
	writer.StartObject();
	  writer.Key("ApplicationNotes");
	  writer.String("The maximum length of the entire message must not exceed 256 bytes.");
	writer.EndObject();

	writer.EndObject();

	str_json = strBuf.GetString();

	return;
}

//解析JSON
void ParseJson(std::string str_json)
{
	if (str_json.empty())
		return;

	rapidjson::Document dom;
	if (!dom.Parse(str_json.c_str()).HasParseError())
	{
		//解析常规Key-Value
		if (dom.HasMember(TEXT("Title")) && dom[TEXT("Title")].IsString())
		{
			std::cout << "【Title】 = " << dom[TEXT("Title")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("Company")) && dom[TEXT("Company")].IsString())
		{
			std::cout << "【Company】 = " << dom[TEXT("Company")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("Keywords")) && dom[TEXT("Keywords")].IsString())
		{
			std::cout << "【Keywords】 = " << dom[TEXT("Keywords")].GetString() << std::endl;
		}
		if (dom.HasMember(TEXT("TotalFunc")) && dom[TEXT("TotalFunc")].IsInt())
		{
			std::cout << "【TotalFunc】 = " << dom[TEXT("TotalFunc")].GetInt() << std::endl;
		}

		//解析数组
		if (dom.HasMember(TEXT("FuncCode")) && dom[TEXT("FuncCode")].IsArray())
		{
			const rapidjson::Value& arrFuncCode = dom[TEXT("FuncCode")];
			int iCount = arrFuncCode.Size();
			for (int ii = 0; ii < iCount;++ii)
			{
				if (arrFuncCode[ii].IsString())
				{
					std::cout << "  【FuncCode】 = " << arrFuncCode[ii].GetString() << std::endl;
				}
			}
		}

		//解析对象
		if (dom.HasMember(TEXT("ErrorCheck")) && dom[TEXT("ErrorCheck")].IsObject())
		{
			const rapidjson::Value& objErrorCheck = dom[TEXT("ErrorCheck")];

			if (objErrorCheck.HasMember(TEXT("Methods")) && objErrorCheck[TEXT("Methods")].IsArray())
			{
				const rapidjson::Value& arrMethods = objErrorCheck[TEXT("Methods")];
				int iCount = arrMethods.Size();
				for (int ii = 0; ii < iCount; ++ii)
				{
					if (arrMethods[ii].IsString())
					{
						std::cout << "  【Methods】 =" << arrMethods[ii].GetString() << std::endl;
					}
				}
			}
		}

		if (dom.HasMember(TEXT("Appendix")) && dom[TEXT("Appendix")].IsObject())
		{
			const rapidjson::Value& objAppendix = dom[TEXT("Appendix")];

			if (objAppendix.HasMember(TEXT("ApplicationNotes")) && objAppendix[TEXT("ApplicationNotes")].IsString())
			{
				std::cout << "【Appendix】 = " << objAppendix[TEXT("ApplicationNotes")].GetString() << std::endl;
			}
		}
	}
}


int main()
{
    std::cout << std::endl;
	std::cout << "------------------------------------Start Make Json---------------------------" << std::endl;

	std::string str_json;
    
	//1.生成JSON
	MakeJson(str_json);
	
	std::cout << str_json << std::endl;

	//2.解析JSON
	std::cout << std::endl;
	std::cout << "------------------------------------Start Parse Json---------------------------" << std::endl;

	ParseJson(str_json);
    
    return 0;
}

运行截图
在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐