Nefarious
Nefarious

Reputation: 516

Flutter/Dart Json Serialization

I am new to both Flutter and Dart and trying to convert some android studio application to use flutter if I can. I am trying to parse some simple json to learn how all of the dart/flutter features can help me.

The class structure that I want to write to is:

class Company extends Salinas {
  final String name;
  Company({this.name}) : super();

  factory Company.fromJson(Map<String, dynamic> json) => _$CompanyFromJson(json);
  Map<String, dynamic> toJson() => _$CompanyToJson(this);
}

class Salinas {
  final int id;
  Salinas({this.id});

  factory Salinas.fromJson(Map<String, dynamic> json) => _$SalinasFromJson(json);
  Map<String, dynamic> toJson() => _$SalinasToJson(this);
}

the json string is simple

 {"id":1,"name":"Acme"}

and:

 print(company.id)is null
 print(company.name) is Acme;

when I look at the Company.g.dart file there is no reference to the extended class Salinas? is there a way to do this?

I'm clearly missing something.

Upvotes: 1

Views: 1104

Answers (2)

Darsh Shah
Darsh Shah

Reputation: 1666

class Company {
  int id;
  String name;

  Company({this.id, this.name});

  Company.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
}

On the basis of JSON you have provided, you should have made a Model as above. After that, you can map the whole thing quite conveniently,

Company company = Company.fromJson(response);

and then you are free to print

print(company.id);
print(company.name);

Upvotes: 1

Akif
Akif

Reputation: 7660

You need to define extended class properties in child constructor like this:

  class Company extends Salinas {
     final String name;
     Company({id, this.name}) : super(id: id);
   }

After you will see this result:

   print(company.id) is 1
   print(company.name) is Acme;

Upvotes: 1

Related Questions