Skip to content

Commit 7bf2ad2

Browse files
committed
Introduce JsonEncode helper function
It's just a wrapper around the `JsonEncoder` class to simplify its usage.
1 parent 1e3f9d6 commit 7bf2ad2

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

lib/base/json.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,19 @@ String icinga::JsonEncode(const Value& value, bool pretty_print)
304304
}
305305
}
306306

307+
/**
308+
* Serializes an Icinga Value into a JSON object and writes it to the given output stream.
309+
*
310+
* @param value The value to be JSON serialized.
311+
* @param os The output stream to write the JSON data to.
312+
* @param prettify Whether to pretty print the serialized JSON.
313+
*/
314+
void icinga::JsonEncode(const Value& value, std::ostream& os, bool prettify)
315+
{
316+
JsonEncoder encoder(os, prettify);
317+
encoder.Encode(value);
318+
}
319+
307320
Value icinga::JsonDecode(const String& data)
308321
{
309322
String sanitized (Utility::ValidateUTF8(data));

lib/base/json.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ class JsonEncoder
218218
};
219219

220220
String JsonEncode(const Value& value, bool pretty_print = false);
221+
void JsonEncode(const Value& value, std::ostream& os, bool prettify = false);
221222
Value JsonDecode(const String& data);
222223

223224
}

test/base-json.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,14 @@ BOOST_AUTO_TEST_CASE(encode)
3939
"string": "LF\nTAB\tAUml\u00e4Ill\ufffd",
4040
"true": true,
4141
"uint": 23
42-
}
43-
)EOF");
42+
})EOF");
43+
44+
auto got(JsonEncode(input, true));
45+
BOOST_CHECK_MESSAGE(output == got, "expected=" << output << "\ngot=" << got);
4446

45-
BOOST_CHECK(JsonEncode(input, true) == output);
47+
std::ostringstream oss;
48+
JsonEncode(input, oss, true);
49+
BOOST_CHECK_MESSAGE(oss.str() == output, "expected=" << output << "\ngot=" << oss.str());
4650

4751
boost::algorithm::replace_all(output, " ", "");
4852
boost::algorithm::replace_all(output, "Objectoftype'Function'", "Object of type 'Function'");

0 commit comments

Comments
 (0)