1
2
3
4
5
6 #ifndef SOULNG_UTIL_JSON_INCLUDED
7 #define SOULNG_UTIL_JSON_INCLUDED
8 #include <soulng/util/UtilApi.hpp>
9 #include <string>
10 #include <map>
11 #include <memory>
12 #include <vector>
13
14 namespace soulng { namespace util {
15
16 enum class JsonValueType
17 {
18 object, array, string, number, boolean, null
19 };
20
21 class CodeFormatter;
22
23 class JsonValue
24 {
25 public:
26 JsonValue(JsonValueType type_);
27 JsonValue(const JsonValue&) = delete;
28 JsonValue& operator=(const JsonValue&) = delete;
29 virtual ~JsonValue();
30 virtual JsonValue* Clone() const = 0;
31 JsonValueType Type() const { return type; }
32 virtual std::string ToString() const = 0;
33 virtual void Write(CodeFormatter& formatter);
34 private:
35 JsonValueType type;
36 };
37
38 class JsonString : public JsonValue
39 {
40 public:
41 JsonString();
42 JsonString(const std::u32string& value_);
43 void Append(char32_t c);
44 JsonValue* Clone() const override;
45 const std::u32string& Value() const { return value; }
46 void SetValue(const std::u32string& value_);
47 std::u16string JsonCharStr(char32_t c) const;
48 std::string ToString() const override;
49 private:
50 std::u32string value;
51 };
52
53 class JsonNumber : public JsonValue
54 {
55 public:
56 JsonNumber();
57 JsonNumber(double value_);
58 JsonValue* Clone() const override;
59 double Value() const { return value; }
60 std::string ToString() const override;
61 private:
62 double value;
63 };
64
65 class JsonBool : public JsonValue
66 {
67 public:
68 JsonBool();
69 JsonBool(bool value_);
70 JsonValue* Clone() const override;
71 bool Value() const { return value; }
72 std::string ToString() const override;
73 private:
74 bool value;
75 };
76
77 class JsonObject : public JsonValue
78 {
79 public:
80 JsonObject();
81 void AddField(const std::u32string& fieldName, std::std::unique_ptr<JsonValue>&&fieldValue);
82 JsonValue* GetField(const std::u32string& fieldName);
83 std::string GetStringField(const std::u32string& fieldName);
84 JsonValue* Clone() const override;
85 std::string ToString() const override;
86 void Write(CodeFormatter& formatter) override;
87 private:
88 std::vector<std::std::unique_ptr<JsonValue>>fieldValues;
89 std::map<std::u32string, JsonValue*> fieldMap;
90 };
91
92 class JsonArray : public JsonValue
93 {
94 public:
95 JsonArray();
96 void AddItem(std::std::unique_ptr<JsonValue>&&item);
97 int Count() const { return items.size(); }
98 JsonValue* operator[](int index) const;
99 JsonValue* Clone() const override;
100 std::string ToString() const override;
101 void Write(CodeFormatter& formatter) override;
102 private:
103 std::vector<std::std::unique_ptr<JsonValue>>items;
104 };
105
106 class JsonNull : public JsonValue
107 {
108 public:
109 JsonNull();
110 JsonValue* Clone() const override;
111 std::string ToString() const override;
112 };
113
114 } }
115
116 #endif // SOULNG_UTIL_JSON_INCLUDED