FlutterJsonToDart使用

FlutterJsonToDart插件使用

1、在AndroidStudio的setting->plugins中查找FlutterJsonToDart并安装,让后重启AndroidStudio


2、选择mode需要存放的文件夹新建dart文件


3、在插件面板中写入需要序列化的json合文件名称


确认后会自动生成.dart和.g.dart文件


Json_serializable使用

1. 使用 @JsonKey 注解定制字段行为

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()

class User {

  @JsonKey(name: 'user_id') // JSON 中的 key 是 user_id,Dart 中是 userId

  final int userId;

  @JsonKey(includeIfNull: false) // 序列化时忽略 null 值

  final String? nickname;

  User(this.userId, this.nickname);

}


2. 使用 @JsonSerializable 的参数定制类级别行为

@JsonSerializable(

  explicitToJson: true,      // 子对象也使用 toJson

  includeIfNull: false,      // 整体不包含 null 字段

  fieldRename: FieldRename.snake, // 自动将驼峰转为下划线命名

)

class MyModel { ... }


3. 手动编写 fromJson / toJson 并调用生成的方法(高级用法)

如果你有部分逻辑需要自定义,可以在你的 model 类中写自己的 fromJson,然后委托给生成的私有方法:

factory MyModel.fromJson(Map<String, dynamic> json) {

  // 在这里做预处理

  if (!json.containsKey('requiredField')) {

    throw Exception('Missing required field');

  }

  return _$MyModelFromJson(json); // 调用生成的方法

}

Map<String, dynamic> toJson() => _$MyModelToJson(this);


4;@JsonKey(defaultValue: 'Guest')设置默认值

@JsonSerializable()

class User {

  @JsonKey(defaultValue: 'Guest')

  final String name; // 注意:这里声明为非空!

  @JsonKey(defaultValue: 0)

  final int age;

  User({required this.name, required this.age});

  factory User.fromJson(Map<String, dynamic> json) {

    final cleanJson = Map<String, dynamic>.from(json)

      ..removeWhere((key, value) => value == null);

    return _$UserFromJson(cleanJson);

  }

  Map<String, dynamic> toJson() => _$UserToJson(this);

}


注意: @JsonKey(includeIfNull: false) 只能保证序列化toJson时排除null值,如果反序列化fromJson时不会排除null值,这里需要重写方法


import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()

class User {

  final String? name;

  final int? age;

  User({this.name, this.age});

  // 自定义 fromJson:移除所有值为 null 的字段

  factory User.fromJson(Map<String, dynamic> json) {

    // 创建副本避免修改原始数据

    final cleanJson = Map<String, dynamic>.from(json);

    // 移除所有值为 null 的键

    cleanJson.removeWhere((key, value) => value == null);

    return _$UserFromJson(cleanJson);

  }

  Map<String, dynamic> toJson() => _$UserToJson(this);

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容