Reputation: 1951
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?
Upvotes: 1
Views: 1016
Reputation: 122
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.
Upvotes: -1
Reputation: 90145
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;
Upvotes: 4