How to create JSON objects in C++
In C++, third-party libraries can be used to create and manipulate JSON objects. Below is an example of creating a JSON object using the RapidJSON library.
#include <iostream>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
int main() {
// 创建一个空的 JSON 对象
Document document;
document.SetObject();
// 向 JSON 对象中添加键值对
Value name;
name.SetString("John", document.GetAllocator());
document.AddMember("name", name, document.GetAllocator());
Value age;
age.SetInt(30);
document.AddMember("age", age, document.GetAllocator());
// 将 JSON 对象转换为字符串
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);
// 输出 JSON 字符串
std::cout << buffer.GetString() << std::endl;
return 0;
}
The above code utilizes the RapidJSON library. Firstly, we create an empty JSON object named document, and then use the SetObject() method to set it as an empty JSON object.
Next, we created two key-value pairs, one with the key “name” and the value “John” as a string, and the other with the key “age” and the value 30 as an integer. We added these key-value pairs to the JSON object using the AddMember() method.
Finally, we convert the JSON object to a string. We utilize a StringBuffer to store the converted string and use a Writer to convert the JSON object to a string. Lastly, we retrieve the string using the GetString() method and output it using std::cout.
The output result is:
{"name":"John","age":30}
RapidJSON is an efficient library for parsing and generating JSON that makes it easy to create and manipulate JSON objects. Additionally, there are other JSON libraries available for selection, such as nlohmann/json and jsoncpp.