json: extend JsonDispatch flags with nullable and refuse-null flags

currently when dispatching json objects into C structs we either insist
on the field type or we don't. Let's extend this model a bit: depending
on two new fields either allow or refuse null types in addition to the
specified type.

This is useful for example when dispatch enums as this allows us
explicitly refuse null in various scenarios where we allow multiple
types.
This commit is contained in:
Lennart Poettering
2024-06-15 10:58:02 +01:00
committed by Luca Boccassi
parent 26279199cf
commit 3d6c2c918b
3 changed files with 103 additions and 3 deletions
+19 -1
View File
@@ -4656,8 +4656,10 @@ _public_ int sd_json_dispatch_full(
merged_flags = flags | p->flags;
/* If an explicit type is specified, verify it matches */
if (p->type != _SD_JSON_VARIANT_TYPE_INVALID &&
!sd_json_variant_has_type(value, p->type)) {
!sd_json_variant_has_type(value, p->type) &&
!(FLAGS_SET(merged_flags, SD_JSON_NULLABLE) && sd_json_variant_is_null(value))) {
json_log(value, merged_flags, 0,
"Object field '%s' has wrong type %s, expected %s.", sd_json_variant_string(key),
@@ -4672,6 +4674,22 @@ _public_ int sd_json_dispatch_full(
return -EINVAL;
}
/* If the SD_JSON_REFUSE_NULL flag is specified, insist the field is not "null". Note
* that this provides overlapping functionality with the type check above. */
if (FLAGS_SET(merged_flags, SD_JSON_REFUSE_NULL) && sd_json_variant_is_null(value)) {
json_log(value, merged_flags, 0,
"Object field '%s' may not be null.", sd_json_variant_string(key));
if (merged_flags & SD_JSON_PERMISSIVE)
continue;
if (reterr_bad_field)
*reterr_bad_field = p->name;
return -EINVAL;
}
if (found[p-table]) {
json_log(value, merged_flags, 0, "Duplicate object field '%s'.", sd_json_variant_string(key));