skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. I see some issues here.
    Never heard about that json_serialization package, and couldn’t find it in pub.dev.
    You can create Dart objects based on data read from a JSON, but you can’t have NULL properties.

    All properties of a Dart class should be immediately initialized or have a late reference when you give them a value when the initState() is called.

    And a kind reminder that JSON doesn’t require a fixed data format, however, you can force it to always have the required properties, if you control both services that create and read JSON.

    If you use a third-party API or service, you must ensure that the properties exist before using them, and instead of storing every property on a Dart class, you can use a Map<String, Dynamic> to store the JSON content.

    If you really need to have a Dart class to store the values, you should initialize all the String parameters as empty, instead of NULL.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search