flutterdartjson-serialization

How to make all variables not required in json serializable


In json_serialization when i use the annotation @JsonKey(required: false), i am able to make a variable nullable, but then i have to annote all variables with this, it there a way to make this this general for a class, so all the variables can be nullable?

example

enter image description here

is there a way to generalize this?


Solution

  • I think what you want is the includeIfNull property of the @JsonSerializable annotation:

    @JsonSerializable(includeIfNull: true)
    class MyClass {
    ...
    }
    

    This makes all fields nullable by default and includes fields with null values in the serialized output.

    Edit: You will still need to mark the variables as nullable using the question mark, e.g.:

    final String? sender;