dart - 标志忽略属性 build_runner 的序列化
问题描述
有没有办法忽略 JsonSerializable 类中属性的序列化?
我正在使用 build_runner 生成映射代码。
实现此目的的一种方法是在 .g.dart 文件中注释该特定属性的映射,但如果可以在属性上添加忽略属性会很棒。
import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
@JsonSerializable()
class Example {
Example({this.a, this.b, this.c,});
int a;
int b;
/// Ignore this property
int c;
factory Example.fromJson(Map<String, dynamic> json) =>
_$ExampleFromJson(json);
Map<String, dynamic> toJson() => _$ExampleToJson(this);
}
这导致
Example _$ExampleFromJson(Map<String, dynamic> json) {
return Example(a: json['a'] as int, b: json['b'] as int, c: json['c'] as int);
}
Map<String, dynamic> _$ExampleToJson(Example instance) =>
<String, dynamic>{'a': instance.a, 'b': instance.b, 'c': instance.c};
我要做的是通过评论 c 的映射来实现这一点。
Example _$ExampleFromJson(Map<String, dynamic> json) {
return Example(a: json['a'] as int, b: json['b'] as int, c: json['c'] as int);
}
Map<String, dynamic> _$ExampleToJson(Example instance) =>
<String, dynamic>{'a': instance.a, 'b': instance.b, /* 'c': instance.c */};
解决方案
@JsonKey(ignore: true)
在您不想包含的字段之前添加
@JsonKey(ignore: true)
int c;
推荐阅读
- java - 使用 Spring Boot REST 服务的 OffsetDateTime 的偏移量丢失
- vue.js - 如何将 slot 和 slot-scope 移动到 vue 3 v-slot 规则
- azure-active-directory - 图形错误“代码”:“ErrorInvalidIdMalformed”,访问事件/在线会议?
- python - 基于查询集循环查询集
- java - 微服务架构中的请求应该在 1 秒内得到响应
- javascript - 在 Joi 的查询字符串中接受“#”
- asp.net - AntiForgery.Validate(sting1, string2); 给出错误:对类型“HttpContextBase”的引用声称它是在“System.Web”中定义的,但找不到
- c - 检查文件是否包含来自另一个文件 C 的内容
- php - 在 Http 门面中转换 CURL
- elasticsearch - 在常规 Elastic 堆栈中使用 Open Distro 安全插件