Reputation: 1147
so I'm trying to make a register POST request, it's body to be sent should look something like this:
{
"user": {
"email": "[email protected]",
"firstname": "string",
"lastname": "string",
"gender": "female",
"phone_number": "+2120694263542",
"birthdate": "2020-06-24",
"country": "EGY"
}
}
So I've first created a RegisterUpsert model, its class looks like this:
class RegisterUpsert {
String email;
String firstname;
String lastname;
String gender;
String phoneNumber;
String birthdate;
String country;
RegisterUpsert();
RegisterUpsert.fromJson(Map<String, dynamic> json)
: email = json['email'],
firstname = json['firstname'],
lastname = json['lastname'],
gender = json['gender'],
phoneNumber = json['phone_number'],
birthdate = json['birthdate'],
country = json['country'];
Map<String, dynamic> toJson() => {
'email': email,
'firstname': firstname,
'lastname': lastname,
'gender': gender,
'phone_number': phoneNumber,
'birthdate': birthdate,
'country': country,
};
}
Now, I've completed my flow of data collection and processing and have an instance of RegisterUpsert with all the data I need, namely registerBodyFinal
, now I'm trying to call it here:
debugPrint({"user": registerBodyFinal.toJson()}.toString());
showLoading(context);
final response = await http.post(url,
body: {
"user": {registerBodyFinal.toJson()}
}.toString());
Navigator.pop(context);
The debugPrint seems to print the body as I want it, but it seems that's not what's being sent, because trying with postman with the exact debugPrinted lines as the body works, but the response on the flutter app indicates the server is getting an improper/missing JSON. what distinction could be made between the first body I show in this question, and the body I'm posting in flutter?
My guess is that parsing with toString parses all my brackets and so on as a part of a string and that breaks it? but then unless I use the .toString() I get a castError on runtime:
InternalLinkedHashMap<String,Dynamic> is not a subtype of type 'String' in type cast
Thanks for any help.
Upvotes: 0
Views: 113
Reputation: 51722
When you have a tree of JSON, don't encode parts of it and then further enclose those in parent maps. Enclose the maps (or classes with toJson
methods returning maps) inside the parent maps and finally call json.encode
once on the root map (or list).
The correct syntax you need is:
var upsert = RegisterUpsert()
..email = 'e'
..firstname = 'f'
..lastname = 'l'
..gender = 'f'
..phoneNumber = 'ph'
..birthdate = 'today'
..country = 'nl';
var bodyMap = <String, dynamic>{'user': upsert};
final response = await http.post(url, body: json.encode(bodyMap));
Upvotes: 1