flutter开发实战-jsontodart及 生成Dart Model类。 在开发中,经常遇到请求的数据Json需要转换成model类。这里记录一下Jsontodart生成Dart Model类的方案。

一、JSON生成Dart Model类

在开发中经常用到将json转成map或者list。通过json.decode() 可以方便 JSON 字符串转为 List/Map 如

{

"name": "Bruce",

"age": 20

}

转换成Map

Map user = json.decode(json);

在自定义类中经常将请求封装,最后将请求转换成Map通过Dio请求服务器。

class UserInfoReq {

int? id;

int? timestamp;

UserInfoReq(

{this.id, this.timestamp});

UserInfoReq.fromJson(Map json) {

id = json['id'];

timestamp = json['timestamp'];

}

Map toJson() {

final Map data = new Map();

data['id'] = this.id;

data['timestamp'] = this.timestamp;

return data;

}

}

使用json_annotation、json_serializable、build_runner插件生产Json对应的Dart model

一、引入插件json_annotation、json_serializable、build_runner

在pubspec.yaml引入相应的插件json_annotation、json_serializable、build_runner

dependencies:

flutter:

sdk: flutter

flutter_localizations:

sdk: flutter

# The following adds the Cupertino Icons font to your application.

# Use with the CupertinoIcons class for iOS style icons.

cupertino_icons: ^1.0.2

# JSON注解

json_annotation: ^4.8.0

dev_dependencies:

flutter_test:

sdk: flutter

# JSON转model

json_serializable: ^6.6.1

build_runner: ^2.3.3

二、将Json转成Dart

在开发中经常用到Jsontodart,这里使用的是一下两个 https://javiercbk.github.io/json_to_dart/ https://caijinglong.github.io/json2dart/index_ch.html

将一下Json转成对应的类

{

"name":"Bruce",

"age":20

}

对应的dart类

import 'package:json_annotation/json_annotation.dart';

part 'user_info_dto.g.dart';

@JsonSerializable()

class UserInfoDto extends Object {

@JsonKey(name: 'name')

String name;

@JsonKey(name: 'age')

int age;

UserInfoDto(this.name,this.age,);

factory UserInfoDto.fromJson(Map srcJson) => _$UserInfoDtoFromJson(srcJson);

Map toJson() => _$UserInfoDtoToJson(this);

}

由于这里用到了json_annotation,需要使用命令生成’user_info_dto.g.dart’文件

通过在项目根目录下运行:

flutter packages pub run build_runner build

这触发了一次性构建,可以在需要时为我们的 Model 生成 json 序列化代码,它通过我们的源文件,找出需要生成 Model 类的源文件(包含@JsonSerializable 标注的)来生成对应的 .g.dart 文件。

三、小结

flutter开发实战-jsontodart及 生成Dart Model类。使用json_annotation、json_serializable、build_runner插件生产Json对应的Dart model。

学习记录,每天不停进步。

好文阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: