MCPcopy Create free account
hub / github.com/Icinga/icinga2 / Encode

Method Encode

lib/base/json.cpp:51–94  ·  view source on GitHub ↗

* Encodes a single value into JSON and writes it to the underlying output stream. * * This method is the main entry point for encoding JSON data. It takes a value of any type that can * be represented by our @c Value class recursively and encodes it into JSON in an efficient manner. * If prettifying is enabled, the JSON output will be formatted with indentation and newlines for better * reada

Source from the content-addressed store, hash-verified

49 * to flush the output stream safely when it has not acquired any object lock on the parent containers.
50 */
51void JsonEncoder::Encode(const Value& value, boost::asio::yield_context* yc)
52{
53 switch (value.GetType()) {
54 case ValueEmpty:
55 Write("null");
56 break;
57 case ValueBoolean:
58 Write(value.ToBool() ? "true" : "false");
59 break;
60 case ValueString:
61 EncodeNlohmannJson(value.Get<String>());
62 break;
63 case ValueNumber:
64 EncodeNumber(value.Get<double>());
65 break;
66 case ValueObject: {
67 const auto& obj = value.Get<Object::Ptr>();
68 const auto& type = obj->GetReflectionType();
69 if (type == Namespace::TypeInstance) {
70 static constexpr auto extractor = [](const NamespaceValue& v) -> const Value& { return v.Val; };
71 EncodeObject(static_pointer_cast<Namespace>(obj), extractor, yc);
72 } else if (type == Dictionary::TypeInstance) {
73 static constexpr auto extractor = [](const Value& v) -> const Value& { return v; };
74 EncodeObject(static_pointer_cast<Dictionary>(obj), extractor, yc);
75 } else if (type == Array::TypeInstance) {
76 EncodeArray(static_pointer_cast<Array>(obj), yc);
77 } else if (auto gen(dynamic_pointer_cast<Generator>(obj)); gen) {
78 EncodeValueGenerator(gen, yc);
79 } else {
80 // Some other non-serializable object type!
81 EncodeNlohmannJson(obj->ToString());
82 }
83 break;
84 }
85 default:
86 VERIFY(!"Invalid variant type.");
87 }
88
89 // If we are at the top level of the JSON object and prettifying is enabled, we need to end
90 // the JSON with a newline character to ensure that the output is properly formatted.
91 if (m_Indent == 0 && m_Pretty) {
92 Write("\n");
93 }
94}
95
96/**
97 * Encodes an Array object into JSON and writes it to the output stream.

Callers 3

HandleRequestMethod · 0.45
SendJsonBodyMethod · 0.45
JsonEncodeMethod · 0.45

Calls 4

GetTypeMethod · 0.45
ToBoolMethod · 0.45
GetReflectionTypeMethod · 0.45
ToStringMethod · 0.45

Tested by

no test coverage detected