简体   繁体   English

Flutter/Dart Json 序列化

[英]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.我是 Flutter 和 Dart 的新手,如果可以的话,我试图将一些 android studio 应用程序转换为使用 Flutter。 I am trying to parse some simple json to learn how all of the dart/flutter features can help me.我正在尝试解析一些简单的 json 以了解所有 dart/flutter 功能如何帮助我。

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 json 字符串很简单

 {"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?当我查看 Company.g.dart 文件时,没有提到扩展类 Salinas? is there a way to do this?有没有办法做到这一点?

I'm clearly missing something.我显然错过了一些东西。

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;
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.在您提供的 JSON 的基础上,您应该已经制作了如上的模型。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM