summaryrefslogtreecommitdiff
path: root/AK/JsonObjectSerializer.h
diff options
context:
space:
mode:
authorSergey Bugaev <bugaevc@gmail.com>2019-08-27 14:12:44 +0300
committerAndreas Kling <awesomekling@gmail.com>2019-08-27 14:56:09 +0200
commit56f5c14d86d8abafd798dde1138ff6bd01399fb8 (patch)
treea3bda67fefacacf5a88beaa3d196ac88875dd4af /AK/JsonObjectSerializer.h
parent4ec698d1b01d7efc918fbdd3ac38d2fff839ee62 (diff)
downloadserenity-56f5c14d86d8abafd798dde1138ff6bd01399fb8.zip
JSON: Add JSON serializers
These are two new types that allow serializing JSON on-the-fly as it's generated, without building the whole JSON in memory first.
Diffstat (limited to 'AK/JsonObjectSerializer.h')
-rw-r--r--AK/JsonObjectSerializer.h77
1 files changed, 77 insertions, 0 deletions
diff --git a/AK/JsonObjectSerializer.h b/AK/JsonObjectSerializer.h
new file mode 100644
index 0000000000..1cdb7743fe
--- /dev/null
+++ b/AK/JsonObjectSerializer.h
@@ -0,0 +1,77 @@
+#pragma once
+
+#include <AK/JsonArraySerializer.h>
+#include <AK/JsonValue.h>
+
+namespace AK {
+
+template<typename Builder>
+class JsonObjectSerializer {
+public:
+ explicit JsonObjectSerializer(Builder& builder)
+ : m_builder(builder)
+ {
+ m_builder.append('{');
+ }
+
+ JsonObjectSerializer(const JsonObjectSerializer&) = delete;
+ JsonObjectSerializer(JsonObjectSerializer&&) = delete;
+
+ ~JsonObjectSerializer()
+ {
+ if (!m_finished)
+ finish();
+ }
+
+ void add(const StringView& key, const JsonValue& value)
+ {
+ begin_item(key);
+ value.serialize(m_builder);
+ }
+
+ JsonArraySerializer<Builder> add_array(const StringView& key)
+ {
+ begin_item(key);
+ return JsonArraySerializer(m_builder);
+ }
+
+ JsonObjectSerializer<Builder> add_object(const StringView& key)
+ {
+ begin_item(key);
+ return JsonObjectSerializer(m_builder);
+ }
+
+ void finish()
+ {
+ ASSERT(!m_finished);
+ m_finished = true;
+ m_builder.append('}');
+ }
+
+private:
+ void begin_item(const StringView& key)
+ {
+ if (!m_empty)
+ m_builder.append(',');
+ m_empty = false;
+
+ m_builder.append('"');
+ m_builder.append(key);
+ m_builder.append("\":");
+ }
+
+ Builder& m_builder;
+ bool m_empty { true };
+ bool m_finished { false };
+};
+
+template<typename Builder>
+JsonObjectSerializer<Builder> JsonArraySerializer<Builder>::add_object()
+{
+ begin_item();
+ return JsonObjectSerializer(m_builder);
+}
+
+}
+
+using AK::JsonObjectSerializer;