Home  >  Article  >  Backend Development  >  JSON processing methods and implementation in C++

JSON processing methods and implementation in C++

王林
王林Original
2023-08-21 23:58:432405browse

JSON is a lightweight data exchange format that is easy to read and write, and easy to machine parse and generate. Using JSON format makes it easy to transfer data between various systems. In C, there are many open source JSON libraries for JSON processing. This article will introduce some commonly used JSON processing methods and implementations in C.

JSON Processing Methods in C

  1. RapidJSON

RapidJSON is a fast C JSON parser/generator providing DOM, SAX and in-memory Pool style API. Its main features are as follows:

  • Small memory footprint and fast execution speed;
  • Supports UTF-8, UTF-16, UTF-32 and other encoding formats;
  • Supports C 11 move sematics to make memory management more efficient;
  • Supports SAX-style API, capable of efficient parsing of large JSON files;
  • Supports custom allocation Strategy(allocator).

In RapidJSON, JSON objects can be parsed through DOM and SAX, and the DOM method can be implemented through the Value class. The following is a sample code that uses RapidJSON to generate and parse 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 << "name: " << d["name"].GetString() << endl;
    cout << "age: " << d["age"].GetInt() << endl;

    return 0;
}
  1. Boost.PropertyTree

Boost.PropertyTree is a simple and easy-to-use property processing library that can handle Various attribute formats. Among them, it also supports parsing and generating JSON. Boost.PropertyTree is slightly slower than RapidJSON, but it also has some features:

  • Supports multiple data formats, including INI files, XML and JSON, etc.;
  • Supports the C standard library and BOOST library The data types in;
  • have pluggable data format processing capabilities, and users can write their own extended formats.

The following is a sample code that uses Boost.PropertyTree to generate and parse JSON:

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

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 << endl;

    read_json("test.json", pt);
    cout << "name: " << pt.get<string>("name") << endl;
    cout << "age: " << pt.get<int>("age") << endl;

    return 0;
}
  1. JsonCpp

JsonCpp is a C JSON library , supports code of conduct API and DOM style API. Among them, JsonCpp's DOM API is similar to RapidJSON's Value class. The characteristics of JsonCpp are as follows:

  • supports UTF-8 encoding;
  • supports JSON parsing and generation;
  • provides object-oriented encapsulated API;
  • Support C 11 move sematics.

The following is sample code to generate and parse JSON using JsonCpp:

#include <iostream>
#include <json/json.h>

using namespace std;
using namespace Json;

int main() {
    // 生成JSON
    Value root;
    root["name"] = "Tom";
    root["age"] = 20;
    string json_str = root.toStyledString();
    cout << json_str << endl;

    // 解析JSON
    Reader reader;
    Value value;
    reader.parse("{"name":"Tom","age":20}", value, false);
    cout << "name: " << value["name"].asString() << endl;
    cout << "age: " << value["age"].asInt() << endl;

    return 0;
}
  1. Nlohmann.Json

Nlohmann.Json is a modern , a lightweight, easy-to-use JSON processing library. It provides an object-oriented API and supports C 11 and above standards. The characteristics of Nlohmann.Json are as follows:

  • Single file header implementation, easy to use;
  • Supports multiple STL containers;
  • Very lightweight, headers only;
  • The formatted output is very friendly.

The following is a sample code that uses Nlohmann.Json to generate and parse JSON:

#include <iostream>
#include <nlohmann/json.hpp>

using namespace std;
using json = nlohmann::json;

int main() {
    // 生成JSON
    json j;
    j["name"] = "Tom";
    j["age"] = 20;
    string json_str = j.dump();
    cout << json_str << endl;

    // 解析JSON
    json j2 = json::parse("{"name":"Tom","age":20}");
    cout << "name: " << j2["name"] << endl;
    cout << "age: " << j2["age"] << endl;

    return 0;
}

JSON processing implementation in C

The above introduces four commonly used C JSON processing library, let's take a look at the specific implementation.

  1. RapidJSON implementation

First you need to introduce the RapidJSON library into the project, and then you can use the DOM API to parse and generate JSON. The DOM method is to read the entire JSON object into memory and store it in a Value class.

Generate JSON:

// 生成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 << buffer.GetString() << endl;

Parse JSON:

// 解析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();
  1. Boost.PropertyTree implementation

Using Boost.PropertyTree needs to be in the project Introduce the boost library, and then you can use the ptree class to parse and generate JSON. ptree is a tree structure. After reading JSON, the corresponding value can be obtained through the get function of ptree.

Generate 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 << stream.str() << endl;

Parse JSON:

// 解析JSON
ptree root;
read_json("test.json", root);
const string name = root.get<string>("person.name");
const int age = root.get<int>("person.age");
  1. JsonCpp implementation

Using JsonCpp requires introducing the JsonCpp library into the project. Then you can use the Value class to parse and generate JSON. JsonCpp's Value class supports multiple types of values, such as strings, numbers, Boolean, etc.

Generate JSON:

// 生成JSON
Value root;
Value person;
person["name"] = "Tom";
person["age"] = 20;
root["person"] = person;

cout << root.toStyledString() << endl;

Parse JSON:

// 解析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();
  1. Nlohmann.Json implementation

Using Nlohmann.Json requires json. The hpp file is introduced into the project, and then the json object can be used to parse and generate JSON. Nlohmann.Json provides conversion of various STL container types.

Generate JSON:

// 生成JSON
json j;
j["person"]["name"] = "Tom";
j["person"]["age"] = 20;

cout << j.dump() << endl;

Parse JSON:

// 解析JSON
json j2 = json::parse("{"person":{"name":"Tom","age":20}}");
const string name = j2["person"]["name"];
const int age = j2["person"]["age"];

Summary

This article introduces four commonly used JSON processing libraries in C: RapidJSON, Boost. PropertyTree, JsonCpp and Nlohmann.Json, as well as some of their characteristics and implementation methods. By using these open source libraries, JSON encapsulation parsing and generation can be easily performed. In actual use, developers should choose the JSON library that best suits their project needs to obtain the best results.

The above is the detailed content of JSON processing methods and implementation in C++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn