userver: userver/formats/json/serialize.hpp Source File
Loading...
Searching...
No Matches
serialize.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/json/serialize.hpp
4/// @brief Parsers and serializers to/from string and stream
5
6#include <iosfwd>
7#include <string_view>
8
9#include <fmt/format.h>
10
11#include <userver/formats/json/value.hpp>
12#include <userver/utils/fast_pimpl.hpp>
13#include <userver/utils/fmt_compat.hpp>
14
15USERVER_NAMESPACE_BEGIN
16
17namespace logging {
18
19class LogHelper;
20
21} // namespace logging
22
23namespace formats::json {
24
25constexpr inline std::size_t kDepthParseLimit = 128;
26
27/// Parse JSON from string
28formats::json::Value FromString(std::string_view doc);
29
30/// Parse JSON from stream
31formats::json::Value FromStream(std::istream& is);
32
33/// Serialize JSON to stream
34void Serialize(const formats::json::Value& doc, std::ostream& os);
35
36/// Serialize JSON to string
37std::string ToString(const formats::json::Value& doc);
38
39/// Stably serialize JSON to string. In result there is no whitespace, keys
40/// are sorted and character escaping is stabilized
41std::string ToStableString(const formats::json::Value& doc);
42
43/// @overload
44std::string ToStableString(formats::json::Value&& doc);
45
46/// @see formats::json::ToPrettyString
47struct PrettyFormat final {
48 char indent_char{' '};
49 std::size_t indent_char_count{2};
50};
51
52/// Serialize JSON to a string, using `\n` and indents for objects and arrays.
53std::string ToPrettyString(const formats::json::Value& doc, PrettyFormat format = {});
54
55/// Log JSON
56logging::LogHelper& operator<<(logging::LogHelper&, const formats::json::Value&);
57
58/// Blocking operations that should not be used on main task processor after
59/// startup
60namespace blocking {
61/// Read JSON from file
62formats::json::Value FromFile(const std::string& path);
63} // namespace blocking
64
65namespace impl {
66
67class StringBuffer final {
68public:
69 explicit StringBuffer(const formats::json::Value& value);
70 ~StringBuffer();
71
72 std::string_view GetStringView() const;
73
74private:
75 struct Impl;
76 static constexpr std::size_t kSize = 48;
77 static constexpr std::size_t kAlignment = 8;
78 utils::FastPimpl<Impl, kSize, kAlignment> pimpl_;
79};
80
81} // namespace impl
82
83} // namespace formats::json
84
85USERVER_NAMESPACE_END
86
87template <>
88struct fmt::formatter<USERVER_NAMESPACE::formats::json::Value> : fmt::formatter<std::string_view> {
89 constexpr static auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { return ctx.begin(); }
90
91 template <typename FormatContext>
92 auto format(const USERVER_NAMESPACE::formats::json::Value& value, FormatContext& ctx)
93 USERVER_FMT_CONST->decltype(ctx.out()) {
94 const USERVER_NAMESPACE::formats::json::impl::StringBuffer buffer(value);
95 return formatter<string_view>::format(buffer.GetStringView(), ctx);
96 }
97};