I'm fetching some json data from a rest api server and one of its keys is _id
and I need to serialize this json to a dart object using built_value, but this isn't allowed because in dart _id
is private and built_value doesn't allow me to define a private getter in my model!
So what do I do?
package:built_value
has a mechanism to rename fields. As mentioned in its README.md
:
The corresponding dart class employing
built_value
might look like this. Note that it is using... the@BuiltValueField
annotation to map between the property name on the response and the name of the member variable in thePerson
class.... @nullable @BuiltValueField(wireName: 'first_name') String get firstName;
So in your case, you should be able to do something like:
@BuiltValueField(wireName: '_id')
String get id;
I figured it out! I can replace the _id
with id
like this:
factory User.fromJson(Map<String, dynamic> jsonData) {
Map<String, dynamic> map = {
...jsonData, // add all of jsonData key-value pairs to the map
'id': jsonData['_id'], // assign the value of _id to id
'_id': null, // replace _id value with null
};
return serializers.deserializeWith(User.serializer, map);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.