Search code examples
flutterretrofit

How to send raw json in request body


In Flutter using retrofit package I need to send json raw object as shown in the postman snapshot.

enter image description here

I tried to do it by this method but didn't work

@override
@POST('/profile')
Future<UserModel> updateUser(@Body() UserModel userModel);

this is the request

╔╣ Request ║ POST ║ http://206.189.57.118/api/user/profile 

╔ Headers ╟ content-type: application/json ╟ Accept: application/json ╟ Authorization: Bearer 8|LMoB1zivD3O89B7Bv3RQi4zLMeAfTZShmClvWYAt ╟ contentType: application/json ╟ responseType: ResponseType.json ╟ followRedirects: true ╟ connectTimeout: 0 ╟ receiveTimeout: 0 

 ╔ Body ╟ gender: Male ╟ dateOfBirth: 856800000 ╟ maritalStatus: ╟ numChildren: 0 ╟ address: Khanyounis ╟ phone: 123456789 ╟ secondaryPhone: 123456789 ╟ secondaryPhoneRelationShip: ╟ telephone: 123456789 ╟ university: Azhar ╟ faculty: Software Engineering ╟ specialization: Web development ╟ image: null 

Solution

  • I think it caused you use camel case on your UserModel parameter (ex. dateOfBirth, maritalStatus) and your back end service try to parse key using underscore type (ex. date_of_birth, marital_status).

    To keep using camel case in your dart file and underscore in json/back end service, you can use json_serializable and add JsonKey using underscore. For example

    import 'package:json_annotation/json_annotation.dart';
    part 'user_model.g.dart';
    
    @JsonSerializable()
    class UserModel {
      @JsonKey(name: 'first_name_ar')
      String firstNameAr;
      @JsonKey(name: 'middle_name_ar')
      String middleNameAr;
      @JsonKey(name: 'last_name_ar')
      String lastNameAr;
      @JsonKey(name: 'first_name_en')
      String firstNameEn;
      @JsonKey(name: 'middle_name_en')
      String middleNameEn;
      @JsonKey(name: 'last_name_en')
      String lastNameEn;
      @JsonKey(name: 'gender')
      String gender;
      @JsonKey(name: 'date_of_birth')
      String dateOfBirth;
      @JsonKey(name: 'marital_status')
      String maritalStatus;
      
    
      UserModel();
      factory UserModel.fromJson(Map<String, dynamic> json) =>
          _$UserModelFromJson(json);
      Map<dynamic, dynamic> toJson() => _$UserModelToJson(this);
    }
    

    I use this in my project to send raw json data using retrofit and works.