-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonTool.cpp
85 lines (62 loc) · 1.77 KB
/
JsonTool.cpp
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
#include "JsonTool.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
using namespace Json;
JsonTool* JsonTool::m_singleInstance = nullptr;
JsonTool::JsonTool()
{
StreamWriterBuilder writerBuilder;
writerBuilder["indentation"] = " ";
m_writers[Spaces] = writerBuilder.newStreamWriter();
writerBuilder["indentation"] = "\t";
m_writers[Tab] = writerBuilder.newStreamWriter();
writerBuilder["indentation"] = "";
m_writers[None] = writerBuilder.newStreamWriter();
CharReaderBuilder charBuilder;
m_charReader = charBuilder.newCharReader();
}
JsonTool::~JsonTool()
{
delete m_writers[Spaces];
delete m_writers[Tab];
delete m_writers[None];
delete m_charReader;
}
JsonTool& JsonTool::getInstance()
{
if(!m_singleInstance){
m_singleInstance = new JsonTool();
}
return *m_singleInstance;
}
string JsonTool::valueToJsonString(const Value& value, Indentation indentation) const
{
std::ostringstream dataStream;
// JsonCpp doesn't offer success return value yet
m_writers.at(indentation)->write(value, &dataStream);
return dataStream.str();
}
Value JsonTool::jsonStringToValue(const string& jsonString) const
{
Json::Value value;
string errors;
if(!m_charReader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.size(), &value, &errors)){
cout << errors << endl;
}
return value;
}
Value JsonTool::jsonFileToValue(const std::string& filePath) const
{
Json::Value value;
string errors;
ifstream file(filePath);
if(file.fail()){
return value;
}
string jsonString;
jsonString = string(istreambuf_iterator<char>(file), istreambuf_iterator<char>());
value = jsonStringToValue(jsonString);
return value;
}