Merge pull request #492 from bamkrs/keep_required_fields

Add option to include required fields in JSON even if `value == nullptr` and `includeNullFields == false`.
This commit is contained in:
Benedikt-Alexander Mokroß 2021-10-15 12:57:57 +02:00 committed by GitHub
commit 62b9908971
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 1 deletions

View File

@ -155,11 +155,12 @@ void Serializer::serializeObject(Serializer* serializer,
auto dispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(polymorph.valueType->polymorphicDispatcher);
auto fields = dispatcher->getProperties()->getList();
auto object = static_cast<oatpp::BaseObject*>(polymorph.get());
auto config = serializer->getConfig();
for (auto const& field : fields) {
auto value = field->get(object);
if(value || serializer->getConfig()->includeNullFields) {
if (value || config->includeNullFields || (field->info.required && config->alwaysIncludeRequired)) {
(first) ? first = false : stream->writeSimple(",", 1);
serializeString(stream, (p_char8)field->name, std::strlen(field->name));
stream->writeSimple(":", 1);

View File

@ -65,9 +65,15 @@ public:
/**
* Include fields with value == nullptr into serialized json.
* Field will still be included when field-info `required` is set to true and &id:alwaysIncludeRequired is set to true.
*/
bool includeNullFields = true;
/**
* Always include required fields (set in in DTO_FIELD_INFO) even if they are `value == nullptr`
*/
bool alwaysIncludeRequired = false;
/**
* If `true` - insert string `"<unknown-type>"` in json field value in case unknown field found.
* Fail if `false`.