美文网首页
Flutter json_serializable 自定义注解

Flutter json_serializable 自定义注解

作者: 西风兔 | 来源:发表于2019-11-29 16:58 被阅读0次
为什么需要自定义注解?

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,
}

相关文章

网友评论

      本文标题:Flutter json_serializable 自定义注解

      本文链接:https://www.haomeiwen.com/subject/rqdgwctx.html