Skip to content

include_if_null to exclude non-nullable fields whose toJson() can return null #1184

Open
@andcea

Description

@andcea

A use case is when using constructs such as Optional or Option.
For example:

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable(includeIfNull: false)
class Person {
  final String firstName;

  @JsonKey(includeIfNull: false)
  final Option<String> maybeLastName;

  Person({required this.firstName, required this.maybeLastName});

  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

Running

Person(firstName: "John", maybeLastName: None()).toJson()

will return

{"name": "John", "maybeLastName": null}

which is not what I expect. I expect "maybeLastName" to be excluded from the json given that it's null.
Expected output:

{"name": "John"}

option.toJson() returns null if it's a None and T if it's a Some().

The specific Option implementation I'm using is from fpdart

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions