json: teach json builder "conditional" object fields

Quite often when we generate objects some fields should only be
generated in some conditions. Let's add high-level support for that.
Matching the existing JSON_BUILD_PAIR() this adds
JSON_BUILD_PAIR_CONDITIONAL() which is very similar, but takes an
additional parameter: a boolean condition. If "true" this acts like
JSON_BUILD_PAIR(), but if false then the whole pair is suppressed.

This sounds simply, but requires a tiny bit of complexity: when complex
sub-variants are used in fields, then we also need to suppress them.
This commit is contained in:
Lennart Poettering
2018-11-28 08:38:55 +01:00
parent 2de6225314
commit 319a4f27c4
3 changed files with 149 additions and 34 deletions
+16
View File
@@ -316,6 +316,22 @@ static void test_build(void) {
a = json_variant_unref(a);
b = json_variant_unref(b);
assert_se(json_build(&a, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("x", JSON_BUILD_STRING("y")),
JSON_BUILD_PAIR("z", JSON_BUILD_STRING("a")),
JSON_BUILD_PAIR("b", JSON_BUILD_STRING("c"))
)) >= 0);
assert_se(json_build(&b, JSON_BUILD_OBJECT(
JSON_BUILD_PAIR("x", JSON_BUILD_STRING("y")),
JSON_BUILD_PAIR_CONDITION(false, "p", JSON_BUILD_STRING("q")),
JSON_BUILD_PAIR_CONDITION(true, "z", JSON_BUILD_STRING("a")),
JSON_BUILD_PAIR_CONDITION(false, "j", JSON_BUILD_ARRAY(JSON_BUILD_STRING("k"), JSON_BUILD_STRING("u"), JSON_BUILD_STRING("i"))),
JSON_BUILD_PAIR("b", JSON_BUILD_STRING("c"))
)) >= 0);
assert_se(json_variant_equal(a, b));
}
static void test_source(void) {