【发布时间】: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