15
@POST("api/login")
Call<ApiResponse> loginUser(@Body String user);

Here the string is actually a JSONstring i.e.

{"email":"test@gmail.com","password":"test"}

Couldnt figure out what is wrong in this. Either the string it again converted to json. Please suggest..

This is what i want to do to my request as shown in picture.

enter image description here

Ranjana Dangol
  • 1,319
  • 2
  • 13
  • 24

2 Answers2

28

Convert your data in object

public class Credentials
{
    public String email;
    public String password;
}

Set the data to object

Credentials loginCredentials = new Credentials();
loginCredentials.email = "test@gmail.com";
loginCredentials.password = "password";

Call your api

@POST("api/login")
Call<ApiResponse> loginUser(@Body Credentials credentials);
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • 5
    I dont want to use 'data model' class to send the json to the body. I m searching for alternative. – Ranjana Dangol Jan 29 '16 at 11:10
  • @RanjanaDangol Ok then convert this make `JSON` using `GSON` and saved it in `String` – M D Jan 29 '16 at 11:12
  • 1
    @RanjanaDangol: Wasn't mentioned in you post. Nevermind. :D – Rohit5k2 Jan 29 '16 at 11:12
  • mm.. I tried with GSon converting string to json data, but it doesnt work. is there any other way to pass string such that it would be taken as a json for @BODY . – Ranjana Dangol Jan 29 '16 at 11:14
  • @RanjanaDangol: See if this helps you http://stackoverflow.com/questions/21398598/how-to-post-raw-whole-json-in-the-body-of-a-retrofit-request/21423093#21423093 – Rohit5k2 Jan 29 '16 at 11:17
  • with retrofit 2 you need a model class. No workaround for that. @Rohit5k2 do you mind me asking why `Credentials` is serializable ? – Blackbelt Jan 29 '16 at 11:18
  • @Blackbelt: Nothing specific to this question. If you read my comment on the question post then you will find out this model class is kind of copy paste of my own projects model class (Not the whole part). My project requires it to be serializable. :D. Guess I should remove it because its not relevant to this question. – Rohit5k2 Jan 29 '16 at 11:22
  • I have user model class with other elements too. For this request, I only need email and password, Do you have any way to just send two of the data in custom object class as a @BODY in retrofit. – Ranjana Dangol Jan 29 '16 at 11:41
  • @RanjanaDangol: I don't think that is possible. – Rohit5k2 Jan 29 '16 at 11:48
  • @RanjanaDangol Data model is the way to go if you are not using. then you are denying basic facts :D – silentsudo Jan 30 '16 at 13:40
21
@POST("api/login")
Call<ApiResponse> loginUser(@Body HashMap<String, String> user);

We can use Hasmap here like this.

Ranjana Dangol
  • 1,319
  • 2
  • 13
  • 24