Dart json serialization, how to deal with _id from mongodb being private in Dart?
719
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);
}
Author by
PPP
Updated on December 18, 2022Comments
-
PPP over 1 year
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?