Flutter JSON序列化自动构建

1 依赖包

dependencies:
  # Your other regular dependencies here
  json_annotation: ^2.0.0

dev_dependencies:
  # Your other dev_dependencies here
  build_runner: ^1.0.0
  json_serializable: ^2.0.0

注意 依赖包一定不要写错, json_annotation 和 json_serializable 也不要写反了

2 代码示例

创建了一个 shipmodel.dart 文件 代码如下

import 'package:json_annotation/json_annotation.dart';
part 'shipmodel.g.dart';

@JsonSerializable()
class ShipModel{
  String name;
  @JsonKey(name: 'model')
  String modelName;
  String manufacturer;
  String costInCredits;
  String length;
  String maxAtmospheringSpeed;
  String crew;
  String passengers;
  String cargoCapacity;
  String consumables;
  String hyperdriveRating;
  String mGLT;
  String starshipClass;
  List<String> films;
  String created;
  String edited;
  String url;

   ShipModel( {this.name,
    this.modelName,
    this.manufacturer,
    this.costInCredits,
    this.length,
    this.maxAtmospheringSpeed,
    this.crew,
    this.passengers,
    this.cargoCapacity,
    this.consumables,
    this.hyperdriveRating,
    this.mGLT,
    this.starshipClass,
    this.films,
    this.created,
    this.edited,
    this.url});

  factory ShipModel.fromJson(Map<String,dynamic> json)  => _$ShipModelFromJson(json);
  Map<String, dynamic> toJson() => _$ShipModelToJson(this);

}

有几个关键点 看下,写多了就习惯了

  • 引包 import ‘package:json_annotation/json_annotation.dart’;
  • part生成的文件 格式就是 原文名.g.dart 如 part ‘shipmodel.g.dart’;
  • jsonbean 的字段命名和类型定义
  • getjson 和 tojson 定义 ,这里ShipModel是类名
factory ShipModel.fromJson(Map<String,dynamic> json)  => _$ShipModelFromJson(json);
 Map<String, dynamic> toJson() => _$ShipModelToJson(this);

3 自动生成

在工程目录下 运行命令

flutter packages pub run build_runner build

4 实体类的使用

因为返回对象大概结构如下

{
   "count":37,
   "next":"https://swapi.co/api/starships/?page=2",
   "previous":null,
   "results":[
      {
         "name":"Executor",
         "model":"Executor-class star dreadnought",
         "manufacturer":"Kuat Drive Yards, Fondor Shipyards",
         "cost_in_credits":"1143350000",
         "length":"19000",
         "max_atmosphering_speed":"n/a",
         "crew":"279144",
         "passengers":"38000",
         "cargo_capacity":"250000000",
         "consumables":"6 years",
         "hyperdrive_rating":"2.0",
         "MGLT":"40",
         "starship_class":"Star dreadnought",
         "pilots":[

         ],
         "films":[
            "https://swapi.co/api/films/2/",
            "https://swapi.co/api/films/3/"
         ],
         "created":"2014-12-15T12:31:42.547000Z",
         "edited":"2017-04-19T10:56:06.685592Z",
         "url":"https://swapi.co/api/starships/15/"
      },
      {
         "name":"Sentinel-class landing craft",
         "model":"Sentinel-class landing craft",
         "manufacturer":"Sienar Fleet Systems, Cyngus Spaceworks",
         "cost_in_credits":"240000",
         "length":"38",
         "max_atmosphering_speed":"1000",
         "crew":"5",
         "passengers":"75",
         "cargo_capacity":"180000",
         "consumables":"1 month",
         "hyperdrive_rating":"1.0",
         "MGLT":"70",
         "starship_class":"landing craft",
         "pilots":[

         ],
         "films":[
            "https://swapi.co/api/films/1/"
         ],
         "created":"2014-12-10T15:48:00.586000Z",
         "edited":"2014-12-22T17:35:44.431407Z",
         "url":"https://swapi.co/api/starships/5/"
      }
   ]
}

所以先创建一个 BaseResult类

import 'package:json_annotation/json_annotation.dart';

part 'baseresult.g.dart';


@JsonSerializable()
class BaseResult{
  List<dynamic> results ;

  BaseResult({this.results});

  factory BaseResult.fromJson(Map<String,dynamic> json)  => _$BaseResultFromJson(json);
  Map<String,dynamic>  toJson()  => _$BaseResultToJson(this);
}

执行命令 flutter packages pub run build_runner build
然后就是结合使用了
result.body 就是接口返回的字符串

  var baseResultobj = BaseResult.fromJson(jsonDecode(result.body));
  List<ShipModel>  shopModels = baseResultobj.results
          .map((dynamic d) => ShipModel.fromJson(d))
          .toList();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值