7/20/2016

Use Rapidjson in cpp to read/write json file

  In C++, if you want to serialize, deserialize, prettify JSON, there are some libraries to allow you to do that, e.g. JsonCPP and RapidJson. Compare with JsonCpp and Rapidjon, Rapidjson is faster then JsonCPP. Besides, Rapidjson is a header-only library, so it is easy to include Rapidjon using the different build system, and I have tested and used Rapidjon on my Linux application and android native side.

  There is a snippet of code to serialize and deserialize Json file as bellow.

Write
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <stdio.h>
#include <sys/stat.h>

using namespace rapidjson;
std::stringstream ss_date;
time_t t = time(0);
struct tm * now = localtime(&t);
ss_date << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-'
        << now->tm_mday; 
StringBuffer s;
PrettyWriter<StringBuffer> writer(s);
writer.StartObject();
writer.Key("version");
writer.String("1.0");
writer.Key("data");
writer.String(ss_date.str().c_str());
writer.Key("file");
writer.StartArray();
// m_vWriteFilePath is a vector<std::string> which contains 0.mp3 1.mp3 ...
for (const auto& path : m_vWriteFilePath) {
  writer.String(path.c_str());
}
writer.EndArray();
writer.EndObject();
std::ofstream of(m_indexFilePath);
of << s.GetString();
if (!of.good())
  throw std::runtime_error("Can't write the JSON string to the file!");
Result:
{
    "version": "1.0",
    "data": "2016-7-20",
    "file": [
        "0.mp3",
        "1.mp3",
        "2.mp3",
        "3.mp3",
        "4.mp3"
    ]
}
Read
using namespace rapidjson;
std::stringstream ss;
std::ifstream file(m_indexFilePath);
if (file) {
  ss << file.rdbuf();
  file.close();
} else {
  throw std::runtime_error("!! Unable to open json file");
}
Document doc;
if (doc.Parse<0>(ss.str().c_str()).HasParseError())
  throw std::invalid_argument("json parse error");
// Start parsing json string
std::string version = doc["version"].GetString();
std::string date = doc["data"].GetString();
const Value& array = doc["file"];
for (rapidjson::SizeType i = 0; i < array.Size(); i++) {
  m_vReadFilePath.push_back(array[i].GetString());
}




1 comment:

  1. I don't see where you are deserializing there.

    ReplyDelete