简体   繁体   中英

Feed strings into RapidJson to output JSON

I'm looking at using RapidJSON to convert some data strings to json format. This is what I have as my starting point.

#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;
 }

The output format would be something like this:

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

I'm confused about how I am meant to put my string contents into the json, as well as define that it should be a child of "item".

to produce {"item": {"name": "John", "address": "New York"}} , plz try:

#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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM