flutter学习之Json转model

477 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情

  • 本文主要介绍flutter中json转model

1. 官方json转model

网络请求返回的数据通常是 json格式,因此将 json 格式转换为 model 格外重要。json_serializable地址。 使用在pubspec.yaml 添加 开发环境

dev_dependencies:
 json_serializable: ^6.1.5
 build_runner: ^2.1.8

所有环境

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  json_annotation: ^3.0.1

这里有2个环境,注意 dev_dependencies,这个是开发依赖项,它是开发过程中的一些辅助工具,依赖添加到 dev_dependencies而不是 dependencies。添加完依赖后执行“flutter packages get”,执行完毕就可以使用 json_serializable了。

使用我们可以参考官方的例子

  1. 加入 part 'example.g.dart';
  2. 在需要转换的实体 dart 类 前加入 @JsonSerializable() 注释,标识需要 json序列化处理
  3. fromJson()toJson() 方法的写法是固定模式,按模板修改即可
  4. example.g.dart文件名 需要保持一致,否则执行以下命令无效.
import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable()
class Person {
  /// The generated code assumes these values exist in JSON.
  final String firstName, lastName;

  /// The generated code below handles if the corresponding JSON value doesn't
  /// exist or is empty.
  final DateTime? dateOfBirth;

  Person({required this.firstName, required this.lastName, this.dateOfBirth});

  /// Connect the generated [_$PersonFromJson] function to the `fromJson`
  /// factory.
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  /// Connect the generated [_$PersonToJson] function to the `toJson` method.
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

创建 example.g.dart文件,之后当前项目下执行 image.png

flutter pub run build_runner build  

但是会报错

 出现 问题:Found 1 declared outputs which already exist on disk. This is likely because the`.dart_tool/build` folder was deleted, or you are submitting generated files to your source repository.
 [SEVERE] Conflicting outputs were detected and the build is unable to prompt for permission to remove them. These outputs must be removed manually or the build can be run with `--delete-conflicting-outputs`. The outputs are: lib/models/resp/order_detail_model.g.dart

执行

 flutter packages pub run build_runner build --delete-conflicting-outputs

删除后执行命令进行生成

flutter packages pub run build_runner build lib

也可以执行

flutter pub run build_runner build  

生成

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'example.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Person _$PersonFromJson(Map<String, dynamic> json) => Person(
      firstName: json['firstName'] as String,
      lastName: json['lastName'] as String,
      dateOfBirth: json['dateOfBirth'] == null
          ? null
          : DateTime.parse(json['dateOfBirth'] as String),
    );

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      'firstName': instance.firstName,
      'lastName': instance.lastName,
      'dateOfBirth': instance.dateOfBirth?.toIso8601String(),
    };

2. 插件JsonToDart

如果感觉上面步骤比较繁琐,虽然是官方的。当然我们也可以自己生成model,在 Android Studio 中安装 JsonToDart 插件,打开 Preferences(Mac)或者 Setting(Window),选择 Plugins,搜索 JsonToDart 选定目录,点击右键,选择 New->Json to Dart,或者使用快捷键

  • Windows:ALT + Shift + D
  • Mac:Option + Shift + D

弹出对话框输入json

/// name : "George Perez"
/// content : " 定细世老火采日律类平前身把列者持联数。器识极车史温精离历市名学。务受省越以原法情山十天造参。酸己给式比热约书领元门状路切。条按理本满全商开心至酸北增原。"
/// image : ""

class ChatModel {
  ChatModel({
      String? name, 
      String? content, 
      String? image,}){
    _name = name;
    _content = content;
    _image = image;
}

  ChatModel.fromJson(dynamic json) {
    _name = json['name'];
    _content = json['content'];
    _image = json['image'];
  }
  String? _name;
  String? _content;
  String? _image;

  String? get name => _name;
  String? get content => _content;
  String? get image => _image;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['name'] = _name;
    map['content'] = _content;
    map['image'] = _image;
    return map;
  }

}

3, 小结

flutter中由于没有映射的关系,不像我们iOS中映射关系可以一一映射json转化model。flutter为了不破坏widget的关系,所以设计不能映射。所以我们要手动实现model和json转化的方法。因此我们需要借助三方工具实现这种映射关系