userver: userver/formats/json/serialize.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
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
25/// Parse JSON from string
26formats::json::Value FromString(std::string_view doc);
27
28/// Parse JSON from stream
29formats::json::Value FromStream(std::istream& is);
30
31/// Serialize JSON to stream
32void Serialize(const formats::json::Value& doc, std::ostream& os);
33
34/// Serialize JSON to string
35std::string ToString(const formats::json::Value& doc);
36
37/// Stably serialize JSON to string. In result there is no whitespace, keys
38/// are sorted and character escaping is stabilized
39std::string ToStableString(const formats::json::Value& doc);
40
41std::string ToStableString(formats::json::Value&& doc);
42
43/// Log JSON
44logging::LogHelper& operator<<(logging::LogHelper&,
45 const formats::json::Value&);
46
47/// Blocking operations that should not be used on main task processor after
48/// startup
49namespace blocking {
50/// Read JSON from file
51formats::json::Value FromFile(const std::string& path);
52} // namespace blocking
53
54namespace impl {
55
56class StringBuffer final {
57 public:
58 explicit StringBuffer(const formats::json::Value& value);
59 ~StringBuffer();
60
61 std::string_view GetStringView() const;
62
63 private:
64 struct Impl;
65 static constexpr std::size_t kSize = 48;
66 static constexpr std::size_t kAlignment = 8;
67 utils::FastPimpl<Impl, kSize, kAlignment> pimpl_;
68};
69
70} // namespace impl
71
72} // namespace formats::json
73
74USERVER_NAMESPACE_END
75
76template <>
77struct fmt::formatter<USERVER_NAMESPACE::formats::json::Value>
78 : fmt::formatter<std::string_view> {
79 constexpr static auto parse(format_parse_context& ctx)
80 -> decltype(ctx.begin()) {
81 return ctx.begin();
82 }
83
84 template <typename FormatContext>
85 auto format(const USERVER_NAMESPACE::formats::json::Value& value,
86 FormatContext& ctx) USERVER_FMT_CONST->decltype(ctx.out()) {
87 const USERVER_NAMESPACE::formats::json::impl::StringBuffer buffer(value);
88 return formatter<string_view>::format(buffer.GetStringView(), ctx);
89 }
90};