【问题标题】:Deserialize webapi repsonse to mvc4 viewmodel in application在应用程序中反序列化对 mvc4 viewmodel 的 web api 响应
【发布时间】:2012-03-25 08:34:36
【问题描述】:

我正在尝试设置和使用一个 asp.net webapi REST 应用程序并从另一个项目中使用它。

我做了一个简单的助手来调用服务

public static string GetApiResponse(string apiMethod,Dictionary<string,string>queryString=null)
    {
        using (var client = new WebClient())
        {
            client.Headers.Add("ApiKey", ConfigurationManager.AppSettings["ApiKey"]);
            //add any query string values into the client
            if (queryString != null)
            {
                foreach (var query in queryString)
                {
                    client.QueryString.Add(query.Key, query.Value);
                }
            }
            try
            {
               string url = string.Format("{0}{1}", ConfigurationManager.AppSettings["ApiBaseUrl"],apiMethod);
               return(client.DownloadString(url));
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
    }

我正在另一个项目中从我的控制器中使用它,例如

  private IEnumerable<CustomerModel> CustomerDetails()
    {
        var json = ApiRestHelper.GetApiResponse("Customer/Get");

        var data = JsonConvert.DeserializeObject<CustomerViewModel>(json, new JsonSerializerSettings
                                                                          {

                                                                          });

从服务返回的数据看起来像

[{"CustomerId":"24a62bf8-7a4e-4837-859d-1f04dc983011","FirstName":"Joe","LastName":"Bloggs","StoreCustomerId":null}]

我的 CustomerViewModel 是

 public class CustomerViewModel
{
    public IEnumerable<CustomerModel> Customers { get; set; }
}

我可以看到返回的数据是一个数组,我正在尝试将其转换为列表。我收到一个错误

无法将 JSON 数组(即 [1,2,3])反序列化为“WebApplication.Models.ViewModels.CustomerViewModel”类型。

反序列化的类型必须是数组或实现集合接口,如 IEnumerable、ICollection 或 IList。

我需要进行哪些更改才能将反序列化到我的视图模型中?

【问题讨论】:

    标签: asp.net-mvc json.net asp.net-web-api


    【解决方案1】:

    我试图做错了。

            var data = JsonConvert.DeserializeObject<List<CustomerModel>>(json, new JsonSerializerSettings
                                                                              {
    
                                                                              });
    

    成功了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 2012-12-26
      相关资源
      最近更新 更多