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?
Asked
Active
Viewed 857 times
1

Mahdi Dahouei
- 1,588
- 2
- 12
- 32
2 Answers
4
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;

jamesdlin
- 81,374
- 13
- 159
- 204
-1
You can replace '_id'
with 'id'
once you got JSON Response String. Then serialize it.
Model Class :
@JsonSerializable(explicitToJson: true)
class PersonModel{
int id;
String name;
PersonModel(this.id,this.name);
factory PersonModel.fromJson(Map<String, dynamic> json) => _$PersonModel FromJson(json);
Map<String, dynamic> toJson() => _$PersonModelToJson(this);
}
Replace :
String responseString = response.body
String newResponseString = responseString.replaceAll('_id', 'id');
PersonModel personModel = PersonModel.fromJson(jsonDecode(newResponseString));
Now you can use personModel.id
to access _id
in frontend.

Aditya Birangal
- 82
- 6
-
yes it works, but the best way to do it is to use `@BuiltValueField(wireName: "_id")` attribute – Mahdi Dahouei Jul 22 '22 at 07:51