我有一个使用 Entity Framework 4.1 的 ASP.NET WebApi 项目。我试图返回一个实体并利用 JSON.net 进行反序列化。一切正常,但是当我尝试反序列化具有 TimeSpan 属性的实体时,我遇到了以下异常:
Could not cast or convert from System.String to System.TimeSpan.
查看堆栈跟踪显示:
JsonSerializationException: Error converting value "PT17H9M43.1671969S" to type 'System.TimeSpan'. Path 'TimeIn', line 1, position 890.
response.Content.ReadAsStringAsync().Result
的输出是:
{"CreatedDate":"/Date(1329851383157-0500)/","ServicerUserId":6,"TimeIn":"PT17H9M43.1671969S","TimeOut":"PT17H28M43.1671969S"}
在使用 JSON.net 之前,我已经使用 System.Runtime.Serialization.JsonDataContractJsonSerializer
成功反序列化,但是我不想使用这种方法。
用于从WebApi获取实体的代码
public T Get<T>(object id)
{
using (var httpClient = NewHttpClient())
{
var response = httpClient.GetAsync(_endpoint + id.ToString()).Result;
return JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result);
}
}
WebApi Controller 中用于返回实体的代码:
// GET /api/services/5
public Service Get(Guid id)
{
var entry = db.Services.Find(id);
if (entry == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return entry;
}
任何关于如何反序列化 TimeSpan 的想法都将不胜感激。
最佳答案
解决方案是将 WebApi 项目配置为默认在 global.asax Application_Start 事件中利用 JSON.net 进行序列化,引用 http://blogs.msdn.com/b/henrikn/archive/2012/02/18/using-json-net-with-asp-net-web-api.aspx
// Create Json.Net formatter serializing DateTime using the ISO 8601 format
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
GlobalConfiguration.Configuration.Formatters[0] = new JsonNetFormatter(serializerSettings);
关于c# - 使用 JSON.net 和 .net WebApi 反序列化 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10553294/