user16859477
user16859477

Reputation:

json serializable: variables declared in model class but does not exist in json

I have a problem, I have a simple model class, that has few variables, but, one of them is not necessarily present all the time. but JsonSerializable doesn't convert json to model object if that one key is not available in json data.

Sample code -

import "package:json_annotation/json_annotation.dart";

part "address.g.dart";

@JsonSerializable()
class Address {
  final String country_code, state, city, street_line1, street_line2, post_code;

  Address(this.country_code, this.state, this.city, this.street_line1,
      this.street_line2, this.post_code);

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

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

So as you can see, it is a model class, but street_line2 is not always present. and json serializable doesnot work if it's not present.

Upvotes: 0

Views: 463

Answers (1)

novol
novol

Reputation: 852

use "?" for nullable variables in your model

like this: String? then it can be null

Upvotes: 1

Related Questions