Skip to content

Is it possible to distinguish between absent (no value) and null when serializing? #1123

@GP4cK

Description

@GP4cK

Let's say I have a SimpleValue class with a nullableString:

abstract class SimpleValue implements Built<SimpleValue, SimpleValueBuilder> {
  @BuiltValueSerializer(serializeNulls: true)
  static Serializer<SimpleValue> get serializer => _$simpleValueSerializer;

  String? get nullableString;

  factory SimpleValue([void Function(SimpleValueBuilder) updates]) = _$SimpleValue;
  SimpleValue._();
}

I would like to be able to have this behaviour when serializing to JSON:

final noValue = SimpleValue();
print(serializers.toJson(SimpleValue.serializer, value)); // should print {}

final nullValue = SimpleValue((value) => value.nullableString = null);
print(serializers.toJson(SimpleValue.serializer, nullValue)); // should print { "nullableString": null }

Is it possible?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions