Flutter json_serializable 自定义注解

为什么需要自定义注解?

json_serializable说到底只是一个自动化生成Model类序列号和反序列化代码的插件。

默认配置生成的代码可能不符合我们的要求,比如我们会要求非空值;
比如我们会制定某个属性的key值;

官方给出的自定义注解的三种方式
  1. Set properties on @JsonSerializable. 给@JsonSerializable设置属性
  2. Add a @JsonKey annotation to a field and set properties there. 添加@JsonKey
  3. Add configuration to build.yaml 在yaml中统一配置
以要求value值不能为空为例

让我们分别以以上三种方式完成自定义注解

  1. @JsonSerializable(nullable: false)
  2. @JsonKey(nullable: true)
  3. 在yaml文件中配置
targets:
  $default:
    builders:
      json_serializable:
        options:
          # Options configure how source code is generated for every
          # `@JsonSerializable`-annotated class in the package.
          #
          # The default value for each is listed.
          nullable: true
第二个例子

指定key值

@JsonSerializable()
class User {
    String login;
  
}

当我们使用默认配置时,生成的.g.dart文件是

User _$UserFromJson(Map<String, dynamic> json) {
  return User()
    ..login = json['login'] as String
}
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'login': instance.login,
}

当我们使用Jsonkey自定义时,生成的.g.dart文件则是

User _$UserFromJson(Map<String, dynamic> json) {
  return User()
    ..login = json['isLogin'] as String
}
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
      'isLogin': instance.login,
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容