Luc*_*lla 2 json mongodb dart flutter
我在 dart 中使用自动序列化/反序列化,就像这里提到的那样
import 'package:json_annotation/json_annotation.dart';
part 'billing.g.dart';
@JsonSerializable()
class Billing {
Billing(){}
String _id;
String name;
String status;
double value;
String expiration;
factory Billing.fromJson(Map<String, dynamic> json) => _$BillingFromJson(json);
Map<String, dynamic> toJson() => _$BillingToJson(this);
}
Run Code Online (Sandbox Code Playgroud)
但为了使序列化/反序列化正常工作,这些字段必须是公共的。_然而,在 Dart 中,开头为 的字段是私有的。所以我不能使用_idmongodb 来序列化/反序列化。
我怎样才能克服这个问题?
您可以使用@JsonKey注释。请参阅https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/name.html
import 'package:json_annotation/json_annotation.dart';
part 'billing.g.dart';
@JsonSerializable()
class Billing {
Billing(){}
// Tell json_serializable that "_id" should be
// mapped to this property.
@JsonKey(name: '_id')
String id;
String name;
String status;
double value;
String expiration;
factory Billing.fromJson(Map<String, dynamic> json) => _$BillingFromJson(json);
Map<String, dynamic> toJson() => _$BillingToJson(this);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1309 次 |
| 最近记录: |