我正在尝试将数据从Android应用程序发送到asp.net web api,我有两个值来发送登录名和密码,我把它们放在NameValuePair列表中并发送它们。这是我的代码:
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);
如何在web api项目中反序列化json? 这是我想要反序列化Json的函数:
[AcceptVerbs("POST")]
public string login([FromBody] object data)
{
//Here I want to get the login and password values from the json.
}
答案 0 :(得分:2)
你为什么要这么复杂?您可以在WebApi中创建简单的POCO类,如下所示:
public class LoginModel
{
public string Email { get; set; }
public string Password { get; set; }
}
并在您的方法中执行以下操作:
[AcceptVerbs("POST")]
public string login(LoginModel loginModel)
{
//loginModel.Email and loginModel.Password
}
并在您的请求中,您可以发送JSON字符串,如下所示:
{
"email" : "me@mail.com",
"password": "11111"
}
为WebAPI留下沉重的负担。你可以肯定地用字典做到这一点,但如果你的项目按时间增长,使用模型会更好