Reputation: 1870
I'm using automatic serialization/deserialization in dart like mentioned here
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);
}
But in order for the serialization/deserialization to work, the fields must be public. However, in Dart, a field with _
at the beggining is private. So I can't use _id
from mongodb to serialize/deserialize things.
How can I overcome this?
Upvotes: 2
Views: 1422
Reputation: 1209
You can use @JsonKey annotation. Refer 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);
}
Upvotes: 7