diff options
author | Sergey Bugaev <bugaevc@gmail.com> | 2019-08-27 14:12:44 +0300 |
---|---|---|
committer | Andreas Kling <awesomekling@gmail.com> | 2019-08-27 14:56:09 +0200 |
commit | 56f5c14d86d8abafd798dde1138ff6bd01399fb8 (patch) | |
tree | a3bda67fefacacf5a88beaa3d196ac88875dd4af /AK/JsonArraySerializer.h | |
parent | 4ec698d1b01d7efc918fbdd3ac38d2fff839ee62 (diff) | |
download | serenity-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/JsonArraySerializer.h')
-rw-r--r-- | AK/JsonArraySerializer.h | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/AK/JsonArraySerializer.h b/AK/JsonArraySerializer.h new file mode 100644 index 0000000000..46bbd14ac5 --- /dev/null +++ b/AK/JsonArraySerializer.h @@ -0,0 +1,65 @@ +#pragma once + +#include <AK/JsonValue.h> + +namespace AK { + +template<typename Builder> +class JsonObjectSerializer; + +template<typename Builder> +class JsonArraySerializer { +public: + explicit JsonArraySerializer(Builder& builder) + : m_builder(builder) + { + m_builder.append('['); + } + + JsonArraySerializer(const JsonArraySerializer&) = delete; + JsonArraySerializer(JsonArraySerializer&&) = delete; + + ~JsonArraySerializer() + { + if (!m_finished) + finish(); + } + + void add(const JsonValue& value) + { + begin_item(); + value.serialize(m_builder); + } + + JsonArraySerializer<Builder> add_array() + { + begin_item(); + return JsonArraySerializer(m_builder); + } + + // Implemented in JsonObjectSerializer.h + JsonObjectSerializer<Builder> add_object(); + + void finish() + { + ASSERT(!m_finished); + m_finished = true; + m_builder.append(']'); + } + +private: + void begin_item() + { + if (!m_empty) + m_builder.append(','); + m_empty = false; + } + + Builder& m_builder; + bool m_empty { true }; + bool m_finished { false }; +}; + +} + +using AK::JsonArraySerializer; |