I have following model class.
@JsonSerializable()
class Login {
String? userName;
String? password;
Login({required this.userName, required this.password});
factory Login.fromJson(Map<String, dynamic> json) => _$LoginFromJson(json);
Map<String, dynamic> toJson() => _$LoginToJson(this);
}
Generated part file.
Login _$LoginFromJson(Map<String, dynamic> json) => Login(
userName: json['userName'] as String?,
password: json['password'] as String?,
);
Map<String, dynamic> _$LoginToJson(Login instance) => <String, dynamic>{
'userName': instance.userName,
'password': instance.password,
};
when i try to use it to post to api with follow code
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
Result from the print statement (cause convertion error)
{userName: test, password: password}
Expecting valid json to post is
{
"username": "string",
"password": "string"
}
Error Message
Error: DioError [DioErrorType.other]: Converting object to an encodable object failed: Instance of '_HashSet<String>'
CodePudding user response:
Remove the =>
from
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
to
Future<void> loginUser(Login login) async {
print(login.toJson().toString());
}
In the first example, it is an arrow function where the brackets { }
stand for a set literal since it's right after the arrow, much like in the generated _$LoginToJson
function but without describing the types of the set.
In the second example, it is a normal function the brackets { }
define the body of the function.
You might be looking to call jsonEncode
(import dart:convert;
) which takes a value, such as a Map<String, dynamic>
and turns it into a String
in json format.
Update the print statement as follows:
print(jsonEncode(login.toJson()));
While the generated functions parse the object to a format that is suitable for JSON, it doesn't turn it into an actual String
. You'll need to encode it with jsonEncode
. Similarly, when processing a JSON response, you'll need to jsonDecode
the response body to get a Map<String, dynamic>
structure that you can then pass into the generated fromJson
functions.