userver: userver/dump/json_helpers.hpp Source File
Loading...
Searching...
No Matches
json_helpers.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/dump/json_helpers.hpp
4/// @brief Convenience functions to load and dump as JSON in classes derived
5/// from components::CachingComponentBase.
6
7#include <memory>
8#include <string>
9#include <string_view>
10
11#include <userver/dump/common.hpp>
12#include <userver/dump/operations.hpp>
13#include <userver/dump/unsafe.hpp>
14#include <userver/formats/json/serialize.hpp>
15#include <userver/formats/json/string_builder.hpp>
16#include <userver/formats/json/value.hpp>
17
18USERVER_NAMESPACE_BEGIN
19
20namespace dump {
21
22/// @brief Convenience function to use in
23/// components::CachingComponentBase::WriteContents override to dump a type in
24/// a human readable JSON format.
25///
26/// @see @ref scripts/docs/en/userver/cache_dumps.md
27template <typename T>
28void WriteJson(Writer& writer, const T& contents) {
29 formats::json::StringBuilder sb;
30 WriteToStream(contents, sb);
31 WriteStringViewUnsafe(writer, sb.GetString());
32 WriteStringViewUnsafe(writer, "\n");
33}
34
35/// @brief Convenience function to use in
36/// components::CachingComponentBase::ReadContents override to load a dump in
37/// a human readable JSON format.
38///
39/// @see @ref scripts/docs/en/userver/cache_dumps.md
40template <typename T>
42 return std::make_unique<const T>(
43 formats::json::FromString(ReadEntire(reader)).As<T>());
44}
45
46} // namespace dump
47
48USERVER_NAMESPACE_END