1

I'm trying to send data from android application to asp.net web api, I have two values to send login and password, i put them in NameValuePair List and sent them. Here is my code :

DefaultHttpClient client = new DefaultHttpClient();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("login", getLogin()));
nameValuePair.add(new BasicNameValuePair("password", getPassword()));
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(new GsonBuilder().create().toJson(nameValuePair));
httpPost.setEntity(stringEntity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = client.execute(httpPost);

How can i deserialize the json in the web api project ? Here is the function where I would like to deserialize the Json :

[AcceptVerbs("POST")]
public string login([FromBody] object data)
{
//Here I want to get the login and password values from the json.
}

1 Answer 1

2

Why you are making this complex? You can create simple POCO class in your WebApi as the below:

public class LoginModel 
    {
        public string Email { get; set; }
        public string Password { get; set; }

    }

and in your method you do the following:

[AcceptVerbs("POST")]
public string login(LoginModel loginModel)
{
//loginModel.Email and loginModel.Password
}

and in your request you can send JSON string as the below:

{
  "email" : "[email protected]",
  "password": "11111"
}

And leave the heavy lifting and de-serilization for WebAPI. You can do this with dictionary for sure, but using Models is better if your project grows by time

Sign up to request clarification or add additional context in comments.

4 Comments

As i think i have to create LoginModel in the android project also ?
No you do not, you can send it as JSON string, try doing this first using postman.
@TaiseerJoudehthank you for mentioning postman, didn't know about this tool). Now my life will be much easier
@TaiseerJoudeh How can I send it as Json from my android project ? It didn't worked when I send it in a list of NameValuePair. can you edit your answer to show me how should i do in android side ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.