json是一种轻量级数据交换格式,易于阅读和编写,也易于机器解析和生成。使用json格式可以方便地在各个系统之间传递数据。在c++中,有许多开源的json库可以进行json的处理。本文将介绍一些常用的c++中的json处理方法及实现。
C++中的JSON处理方法
- RapidJSON
RapidJSON是一个快速的C++ JSON解析器/生成器,提供DOM、SAX和内存池样式API。它主要的特点有以下几点:
- 内存占用小,执行速度快;
- 支持UTF-8、UTF-16、UTF-32等多种编码格式;
- 支持C++11的move sematics,使内存管理更加高效;
- 支持SAX风格的API,能够对大型JSON文件进行高效解析;
- 支持自定义分配策略(allocator)。
RapidJSON中,JSON对象可以通过DOM和SAX方式进行解析,其中DOM方式可以通过Value类来实现。以下是一个使用RapidJSON生成并解析JSON的示例代码:
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
using namespace std;
int main() {
// 生成JSON
StringBuffer s;
Writer<stringbuffer> writer(s);
writer.StartObject();
writer.Key("name");
writer.String("Tom");
writer.Key("age");
writer.Int(20);
writer.EndObject();
// 解析JSON
Document d;
d.Parse(s.GetString());
cout <ol start="2"><li>Boost.PropertyTree</li></ol>
<p>Boost.PropertyTree是一个简单易用的属性处理库,能够处理各种属性格式。其中,它也支持解析和生成JSON。Boost.PropertyTree比RapidJSON略慢,但也有一些特点:</p>
<ul>
<li>支持多种数据格式,包括INI文件、XML和JSON等;</li>
<li>支持C++标准库和BOOST库中的数据类型;</li>
<li>具有可插拔的数据格式处理能力,用户可以编写自己的扩展格式。</li>
</ul>
<p>以下是使用Boost.PropertyTree生成并解析JSON的示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <boost>
#include <boost>
using namespace std;
using boost::property_tree::ptree;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
int main() {
// 生成JSON
ptree pt;
pt.put("name", "Tom");
pt.put("age", 20);
// 解析JSON
string json_str;
write_json(cout, pt);
cout ("name") ("age") <ol start="3"><li>JsonCpp</li></ol>
<p>JsonCpp是一个C++的JSON库,支持行为准则API和DOM风格API。其中,JsonCpp的DOM API类似于RapidJSON的Value类。JsonCpp的特点有以下几点:</p>
<ul>
<li>支持UTF-8编码;</li>
<li>支持JSON的解析和生成;</li>
<li>提供面向对象封装的API;</li>
<li>支持C++11的move sematics。</li>
</ul>
<p>以下是使用JsonCpp生成并解析JSON的示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <json>
using namespace std;
using namespace Json;
int main() {
// 生成JSON
Value root;
root["name"] = "Tom";
root["age"] = 20;
string json_str = root.toStyledString();
cout <ol start="4"><li>Nlohmann.Json</li></ol>
<p>Nlohmann.Json是一个现代的,轻量级,易于使用的JSON处理库。它提供了面向对象的API,并支持C++11和以上的标准。Nlohmann.Json的特点有以下几点:</p>
<ul>
<li>单文件头实现,使用方便;</li>
<li>支持多种STL容器;</li>
<li>非常轻量级,headers only;</li>
<li>格式化输出非常友好。</li>
</ul>
<p>以下是使用Nlohmann.Json生成并解析JSON的示例代码:</p>
<pre class="brush:php;toolbar:false;">#include <iostream>
#include <nlohmann>
using namespace std;
using json = nlohmann::json;
int main() {
// 生成JSON
json j;
j["name"] = "Tom";
j["age"] = 20;
string json_str = j.dump();
cout <p>C++中的JSON处理实现</p>
<p>以上介绍了四种常用的C++中JSON处理库,下面我们来看一下具体实现。</p>
<ol><li>RapidJSON实现</li></ol>
<p>首先需要在项目中引入RapidJSON库,然后就可以使用DOM API来进行JSON的解析和生成。DOM方式是将整个JSON对象读入内存,并存储在一个Value类中。</p>
<p>生成JSON:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill10164" title="JSON Formatter"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="JSON Formatter" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill10164" title="JSON Formatter" class="overflowclass">JSON Formatter</a>
<p class="overflowclass">格式化、验证、压缩 JSON 数据并提取路径,以提升可读性与结构验证。</p>
</div>
<a rel="nofollow" href="/xiazai/skill10164" title="JSON Formatter" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">// 生成JSON
Value root(kObjectType);
Value person(kObjectType);
person.AddMember("name", "Tom", allocator);
person.AddMember("age", 20, allocator);
root.AddMember("person", person, allocator);
StringBuffer buffer;
Writer<stringbuffer> writer(buffer);
root.Accept(writer);
cout <p>解析JSON:</p>
<pre class="brush:php;toolbar:false;">// 解析JSON
Document d;
d.Parse("{"person":{"name":"Tom","age":20}}");
const Value& person = d["person"];
const string name = person["name"].GetString();
const int age = person["age"].GetInt();
- Boost.PropertyTree实现
使用Boost.PropertyTree需要在项目中引入boost库,然后就可以使用ptree类进行解析和生成JSON。ptree是一种树形结构,在读入JSON后,可以通过ptree的get函数来获取对应的值。
生成JSON:
// 生成JSON
ptree root;
ptree person;
person.put("name", "Tom");
person.put("age", 20);
root.add_child("person", person);
stringstream stream;
write_json(stream, root);
cout <p>解析JSON:</p><pre class="brush:php;toolbar:false;">// 解析JSON
ptree root;
read_json("test.json", root);
const string name = root.get<string>("person.name");
const int age = root.get<int>("person.age");</int></string>
- JsonCpp实现
使用JsonCpp需要在项目中引入JsonCpp库,然后就可以使用Value类进行JSON的解析和生成。JsonCpp的Value类支持多种类型的值,如字符串、数字、布尔等。
生成JSON:
// 生成JSON
Value root;
Value person;
person["name"] = "Tom";
person["age"] = 20;
root["person"] = person;
cout <p>解析JSON:</p><pre class="brush:php;toolbar:false;">// 解析JSON
Reader reader;
Value value;
string json_str = "{"person":{"name":"Tom","age":20}}";
reader.parse(json_str, value);
const string name = value["person"]["name"].asString();
const int age = value["person"]["age"].asInt();
- Nlohmann.Json实现
使用Nlohmann.Json需要将json.hpp文件引入到项目中,然后就可以使用json对象进行JSON的解析和生成。Nlohmann.Json提供了各种STL容器类型的转换。
生成JSON:
// 生成JSON
json j;
j["person"]["name"] = "Tom";
j["person"]["age"] = 20;
cout <p>解析JSON:</p><pre class="brush:php;toolbar:false;">// 解析JSON
json j2 = json::parse("{"person":{"name":"Tom","age":20}}");
const string name = j2["person"]["name"];
const int age = j2["person"]["age"];
总结
本文介绍了C++中四种常用的JSON处理库:RapidJSON、Boost.PropertyTree、JsonCpp和Nlohmann.Json,以及它们的一些特点和实现方法。通过使用这些开源库,可以方便地进行JSON的封装解析和生成。在实际使用中,开发人员应该选择最适合自己项目需求的JSON库,以获得最佳的使用效果。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










