将字符串输入 RapidJson 以输出 JSON

Feed strings into RapidJson to output JSON

我正在考虑使用 RapidJSON 将一些数据字符串转换为 json 格式。这就是我的出发点。

#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;
using namespace std;

std::string item_name
std::string item_address

itemname = "John";
item_address = "New York";

int main() {
 StringBuffer s;
 writer<StringBuffer> writer(s);

 writer.StartObject();
 writer.String("hello");
 writer.EndObject();

 std:cout << s.GetString() <<endl;
 return 0;
 }

输出格式应该是这样的:

{"item": {"name": "John", "address": "New York"}}

我对如何将我的字符串内容放入 json 以及定义它应该是 "item" 的子项感到困惑。

生成{"item": {"name": "John", "address": "New York"}},请尝试:

#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <string>

using namespace rapidjson;
using namespace std;

std::string item_name;
std::string item_address;

int main() {
    item_name = "John";
    item_address = "New York";

    StringBuffer s;
    Writer<StringBuffer> writer(s);

    writer.StartObject();
    writer.String("item");
        writer.StartObject();
        writer.String("name");
        writer.String(item_name.c_str());
        writer.String("address");
        writer.String(item_address.c_str());
        writer.EndObject();
    writer.EndObject();

    std:cout << s.GetString() <<endl;
    return 0;
 }