RapidJSON的使用

RapidJSON是一个轻量级的C++ JSON库,仅包含头文件,使用时将其'include/rapidjson'目录添加到项目路径。通过premake工具进行项目构建。文章介绍了如何构建RapidJSON项目,并提供了在Windows上使用不同Visual Studio版本的示例,以及如何在项目中引入并使用RapidJSON。

关于RapidJSON


rapidjson项目地址:https://github.com/miloyip/rapidjson


项目下载完成后,打开readme.md文件,查看项目说明。

RapidJSON is a header-only C++ library. Just copy the `include/rapidjson` folder to system or project's include path.

RapidJSON是一个只有头文件的C++ JSON库,只需要拷贝“include/rapidjson”目录到工程包含路径下即可使用。


文档说明地址:ttp://miloyip.github.io/rapidjson/


项目的构建


RapidJSON项目的构建需要使用一个工具,就是premake。

premake是一个跨平台项目构建工具。

premake下载地址:http://industriousone.com/premake/download


项目构建过程:

premake下载完成后,把premake4.exe文件解压到build目录下,点击premake.bat(Windows),如果是Linux/Mac则点击premake.sh,生成项目。


这里是windows平台下的项目构建,vs2005、vs2008、vs2010分别是不同版本的Visual Studio项目,打开解决方案后,可以看到一些RapidJSON库的使用示例。



RapidJSON的使用


1.拷贝include\rapidjson文件夹到项目路径下。

2.引入rapidjson库头文件


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

using namespace rapidjson;

3.rapidjson的使用

	const char* str = "{\"name\":\"xiaoming\",\"age\":18,\"job\":\"coder\",\"a\":{\"b\":1}}";

	Document doc;
	// 在DOM中解析json字符串
	doc.Parse(str);

	// 读取json数据
	const Value& age = doc["age"];	
	printf("age=%d \n",age.GetInt());
	// 修改json数据
	age.SetString("data is change");

	// 读取对象中的对象
	const Value& b = doc["a"]["b"];
	printf("b=%d \n",b.GetInt());

	// 序列化
	StringBuffer buff;
	Writer
  
    writer(buff);
	doc.Accept(writer);

	// 打印json字符串
	printf(buff.GetString());
const char* name = "xiaoming";
	int age = 18;
	double height = 1.64;

	StringBuffer buff;
	Writer
   
     writer(buff);
	
	writer.StartObject();

	writer.String("name");	
	//writer.String(name,10); 第二个参数用于设置写入字符串长度,如果超出字符串长度会有垃圾数据
	writer.String(name);

	writer.String("age");
	writer.Int(age);

	writer.String("height");
	writer.Double(height);

	// 数组
	writer.String("arr");
	writer.StartArray();	
	for (int i=0;i<5;++i)
	{
		writer.Int(i);
	}
	writer.EndArray();

	writer.EndObject();
	
	printf(buff.GetString());
const char* str = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\"}]}";

	Document doc;
	doc.Parse(str);	

	if (doc.HasParseError() == false)
	{		
		const Value& employees = doc["employees"];

		// rapidjson uses SizeType instead of size_t.
		for (SizeType i = 0; i < employees.Size(); i++)
		{
			const Value& temp = employees[i];

			printf("firstName=%sďźu008ClastName=%s \n",temp["firstName"].GetString(),temp["lastName"].GetString());
		}        
	}else{
		printf("parse error\n");
	}
StringBuffer buff;
	Writer
    
      writer(buff);

	writer.StartArray();
	for (int i=0;i<5;++i)
	{
		writer.Int(i);
	}	
	writer.EndArray();

	printf("%s",buff.GetString());

    
   
  


测试工程地址:https://coding.net/u/linchaolong/p/RapidJSONTest/git

点击下载源码


RapidJSON是一个高效的C++ JSON解析器和生成器,支持现代的JSON特性,如嵌套对象、数组、Unicode编码和注释,其API简洁易用,可以轻松解析和生成JSON数据[^2]。以下是一些常见的使用场景及示例代码: #### 解析JSON字符串 ```cpp #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <iostream> using namespace rapidjson; int main() { const char* json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; Document d; d.Parse(json); if (d.HasMember("name") && d["name"].IsString()) { std::cout << "Name: " << d["name"].GetString() << std::endl; } if (d.HasMember("age") && d["age"].IsInt()) { std::cout << "Age: " << d["age"].GetInt() << std::endl; } if (d.HasMember("city") && d["city"].IsString()) { std::cout << "City: " << d["city"].GetString() << std::endl; } return 0; } ``` #### 生成JSON数据 ```cpp #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <iostream> using namespace rapidjson; int main() { Document d; d.SetObject(); Document::AllocatorType& allocator = d.GetAllocator(); Value name; name.SetString("Alice", allocator); d.AddMember("name", name, allocator); d.AddMember("age", 25, allocator); Value city; city.SetString("Los Angeles", allocator); d.AddMember("city", city, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); std::cout << buffer.GetString() << std::endl; return 0; } ``` #### 在Cocos2d-x中使用 在Cocos2d-x - 2.2.2的版本中,将Jsoncpp的库替换成了rapidJson,因为rapidJson的解析效率要高于Jsoncpp [^3]。以下是一个简单的在Cocos2d-x中使用rapidJson进行JSON解析的示例: ```cpp #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "cocos2d.h" USING_NS_CC; void parseJson(const std::string& jsonStr) { rapidjson::Document d; d.Parse(jsonStr.c_str()); if (d.HasMember("key") && d["key"].IsString()) { std::string value = d["key"].GetString(); CCLOG("Value of key: %s", value.c_str()); } } ```
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值