Writing to JSON file

Hi everyone,

I have some configration information stored in a json file. I can read it with the rapidjson, but got in troubles when trying to make changes.

I have tried something like this:

FileStream f(stdout);
PrettyWriter<FileStream> writer(f);
document.Accept(writer);

but get the next errors:

../Classes/State.cpp:193:2: error: ‘FileStream’ was not declared in this scope
  FileStream f(stdout);
  ^
../Classes/State.cpp:193:13: error: expected ‘;’ before ‘f’
  FileStream f(stdout);
             ^
../Classes/State.cpp:194:2: error: ‘PrettyWriter’ was not declared in this scope
  PrettyWriter<FileStream> writer(f);
  ^
../Classes/State.cpp:194:34: error: ‘f’ was not declared in this scope
  PrettyWriter<FileStream> writer(f);
                                  ^
../Classes/State.cpp:194:35: error: ‘writer’ was not declared in this scope
  PrettyWriter<FileStream> writer(f);

Can anyone give me any advice about this?

Seems like a dumb question, but are you sure you’re including the headers containing FileStream and PrettyWriter? Also make sure you’re using the proper namespace.

I have found the solution. Maybe it will help someone.

#include "CocoStudio/Json/rapidjson/stringbuffer.h"
#include "CocoStudio/Json/rapidjson/prettywriter.h"
GenericStringBuffer< UTF8<> > buffer;
Writer< GenericStringBuffer< UTF8<> > > writer(buffer);
document.Accept(writer);

FILE* file;
file = fopen("config.json","w");
fprintf(file, "%s", buffer.GetString());
1 Like

Ah I had no idea rapidjson was included in cocos now, cool!

Another solution for those who may need it:

#include <fstream>
#include "external/json/stringbuffer.h"
#include "external/json/writer.h"
void JsonParser::JsonToFile(rapidjson::Document &jsonObject, std::string &fullpath) {
    std::ofstream outputFile;
    outputFile.open(fullpath);
    if(outputFile.is_open()) {
        std::string jsonObjectData = JsonToString(jsonObject);
        outputFile << jsonObjectData;
    }
    outputFile.close();
}

std::string JsonParser::JsonToString(rapidjson::Document &jsonObject) {
	rapidjson::StringBuffer buffer;
	rapidjson::Writer<rapidjson::StringBuffer> jsonWriter(buffer);
	jsonObject.Accept(jsonWriter);
	return buffer.GetString();
}
2 Likes