-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonUtil.h
87 lines (65 loc) · 1.72 KB
/
jsonUtil.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#pragma once
#include <cstdio>
#include <boost/filesystem.hpp>
#define RAPIDJSON_HAS_STDSTRING 1
#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
#include <rapidjson/prettywriter.h>
#include <rapidjson/document.h>
typedef rapidjson::PrettyWriter<rapidjson::StringBuffer> JsonWriterBase;
typedef rapidjson::Document JsonReaderBase;
typedef rapidjson::Value JsonValue;
struct JsonWriter : public JsonWriterBase
{
rapidjson::StringBuffer strBuf;
JsonWriter();
void Save(std::string _fPath);
};
struct JsonReader : public JsonReaderBase
{
bool Load(std::string _fPath);
};
inline JsonWriter::JsonWriter()
: JsonWriterBase(strBuf)
{
SetIndent('\t', 1);
StartObject();
}
inline void JsonWriter::Save(std::string _fPath)
{
_fPath += ".json";
EndObject();
::FILE *pFile = ::fopen(_fPath.c_str(), "wb");
::fwrite(strBuf.GetString(), sizeof(decltype(strBuf)::Ch), strBuf.GetLength(), pFile);
::fclose(pFile);
}
inline bool JsonReader::Load(std::string _fPath)
{
_fPath += ".json";
namespace fs = boost::filesystem;
if (!fs::is_regular_file(_fPath))
return false;
::FILE *pFile = ::fopen(_fPath.c_str(), "rb");
::fseek(pFile, 0, SEEK_END);
long fSize = ::ftell(pFile);
::rewind(pFile);
std::vector<char> content;
content.resize(sizeof(char) * fSize + 1);
size_t result = ::fread(content.data(), sizeof(char), fSize, pFile);
assert(result == fSize);
::fclose(pFile);
content.back() = '\0';
if (Parse(content.data()).HasParseError()) {
#ifdef _DEBUG
#ifdef _WIN
pFile = ::fopen("r:/err.json", "wb");
#elif defined(_APPLE)
pFile = ::fopen("/Volumes/RamDisk/err.json", "wb");
#endif
::fwrite(content.data(), sizeof(char), content.size(), pFile);
::fclose(pFile);
assert(false);
#endif
return false;
}
return true;
}