I would be great if mobx_codegen emmited some form of serialization/deserialization functions for Observable objects. toJson/fromJson or something like this.
Great idea. By default we can generate the code that only includes the Observable properties. Computed will be skipped.
Lot of this functionality overlaps with what is offered by json_serializable. Perhaps we can take a dependency on it?
Marking the mixed class with @JsonSerializable works for me:
@JsonSerializable(nullable: false)
class User extends _User with _$User {
User(int id) : super(id);
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
abstract class _User implements Store {
_User(this.id);
final int id;
@observable
String firstName = 'Jane';
@observable
String lastName = 'Doe';
@computed
String get fullName => '$firstName $lastName';
@action
void updateNames({String firstName, String lastName}) {
if (firstName != null) this.firstName = firstName;
if (lastName != null) this.lastName = lastName;
}
}
generates the Store mixin and the serialization code for User:
User _$UserFromJson(Map<String, dynamic> json) {
return User(json['id'] as int)
..firstName = json['firstName'] as String
..lastName = json['lastName'] as String;
}
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'id': instance.id,
'firstName': instance.firstName,
'lastName': instance.lastName
};
If suppose id is not a string but a Map we have to parse it manually and also we cannot use jsonkey annotation for custom keys
still @katis thanks for your catch your comment helps me to some extent
Closing this for now. json_serializable is the way to go right now.
Most helpful comment
Marking the mixed class with
@JsonSerializableworks for me:generates the Store mixin and the serialization code for User: