Reputation: 57
I am trying to pass List of Custom Object to my API.
Following is my code
import 'package:meta/meta.dart';
import 'package:json_annotation/json_annotation.dart';
part 'submit_survey_question_options_model.g.dart';
@JsonSerializable(nullable: false)
class SubmitSurveyQuestionOptionsModel {
String questionId;
String answer;
SubmitSurveyQuestionOptionsModel(
{@required this.questionId, @required this.answer});
factory SubmitSurveyQuestionOptionsModel.fromJson(
Map<String, dynamic> json) =>
_$SubmitSurveyQuestionOptionsModelFromJson(json);
Map<String, dynamic> toJson() =>
_$SubmitSurveyQuestionOptionsModelToJson(this);
}
Future<SubmitSurveyModel> submitSurvey(
String userId,
String facultyId,
String surveyId,
List<SubmitSurveyQuestionOptionsModel> submitSurveyQuestionOptionList,
String subjectId) async {
Map<String, dynamic> body = {
"userId": userId,
"facultyId": facultyId,
"surveyId": surveyId,
"survey": submitSurveyQuestionOptionList,
"subjectId": subjectId
};
final response = await http.post(
SUBMIT_SURVEY_URL,
body: json.encode(body),
);
SubmitSurveyModel submitSurveyModel = standardSerializers.deserializeWith(
SubmitSurveyModel.serializer, json.decode(response.body));
return submitSurveyModel;
}
I am using json_serializable
in my pubspec
.
I built the serializable class using flutter packages pub run build_runner build
I am not able to figure out what's the problem as the data is not submitted properly?
I have referred the following links but couldn't get it working
Flutter Error: type 'AddressInfo' is not a subtype of type 'String' in type cast
Dart Error Converting Object To JSON
Upvotes: 1
Views: 4444
Reputation: 17249
json.encode(body)
in bodyAdd these two header
'Content-type': 'application/json',
'Accept': 'application/json',
http.post(url,<br>
body: json.encode(body),
headers: { 'Content-type': 'application/json',
'Accept': 'application/json'},
encoding: encoding)
.then((http.Response response) {
// print(response.toString());
}
Upvotes: 0
Reputation: 6277
Try passing the below headers
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
final response = await http.post(Uri.encodeFull(url), body: json.encode(body), headers: headers);
Upvotes: 2