Unable to use std::string in creating members in rapidjason

174 Views Asked by At

I have tried the following code - but getting a compile error

  rapidjson::Document details;
  details.SetObject();
  std::string s = "kjfhgdkgjhfkjfhj";

  details.AddMember("farm", s, details.GetAllocator());

What is the correct way of creating a member with a std::string as a value

1

There are 1 best solutions below

0
A-T On BEST ANSWER

To allow for rapidjson to work with std::strings, add the following pre-processor directive to the beginning of your program.

#define RAPIDJSON_HAS_STDSTRING 1

The following program worked properly for me after adding the above line.

#define RAPIDJSON_HAS_STDSTRING 1

#include<iostream>
#include<rapidjson/rapidjson.h>
#include<rapidjson/document.h>
#include<rapidjson/filewritestream.h>
#include<rapidjson/prettywriter.h>
#include<string>

void writeJSON();

int main() {
    

    writeJSON();
    getchar();
    return 0;
}

void writeJSON() {
    rapidjson::Document doc;
    doc.SetObject();

    std::string s = "kjfhgdkgjhfkjfhj";

    doc.AddMember("farm", s, doc.GetAllocator());

    FILE* fp;
    errno_t err = fopen_s(&fp, "data.json", "wb");

    char writeBuffer[65536];
    rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));

    rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os);
    doc.Accept(writer);

    fclose(fp);

    std::cout << "JSON data written to data.json file" << std::endl;

}