【问题标题】:deserializing json in asp.net web api在asp.net web api中反序列化json
【发布时间】:2015-04-08 17:33:33
【问题描述】:

我正在尝试将数据从 android 应用程序发送到 asp.net web api,我有两个值来发送登录名和密码,我将它们放在 NameValuePair List 中并发送它们。这是我的代码:

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.
}

【问题讨论】:

    标签: json asp.net-web-api


    【解决方案1】:

    你为什么要把这个复杂化?您可以在 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。你当然可以用字典来做到这一点,但如果你的项目随着时间的推移而增长,使用模型会更好

    【讨论】:

    • 我想我也必须在 android 项目中创建 LoginModel 吗?
    • 不,你不这样做,你可以将它作为 JSON 字符串发送,尝试先使用 postman 执行此操作。
    • @TaiseerJoudeh谢谢你提到邮递员,不知道这个工具)。现在我的生活会轻松很多
    • @TaiseerJoudeh 如何从我的 android 项目中将其作为 Json 发送?当我将它发送到 NameValuePair 列表中时,它不起作用。你能编辑你的答案来告诉我我应该如何在 android 端做吗?
    猜你喜欢
    • 2014-04-27
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多