首页 > 解决方案 > 标志忽略属性 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 */};

标签: dartflutterjson-serialization

解决方案


@JsonKey(ignore: true)在您不想包含的字段之前添加

 @JsonKey(ignore: true)
 int c;

另请参阅https://github.com/dart-lang/json_serializable/blob/06718b94d8e213e7b057326e3d3c555c940c1362/json_annotation/lib/src/json_key.dart#L45-L49


推荐阅读