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
RapidJSON is a fast C JSON parser/generator providing DOM, SAX and in-memory Pool style API. Its main features are as follows:
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; }
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:
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; }
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:
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; }
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:
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.
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();
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");
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();
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!