我有一个ASP.NET Web API GET端点
public class MyType
{
public bool Active { get; set; }
public DateTime CreateDate { get; set; }
public int Id { get; set; }
public string Description { get; set; }
}
public class MyResponse
{
public List<MyType> Results { get; set; }
}
[HttpGet]
public MyResponse GetResults()
对于结果包含2个项目的情况,json返回字符串是
{"Results":[{"Active":true,"CreateDate":"2014-01-01T00:00:00","Id":1,"Description":"item 1 description"},{"Active":true,"CreateDate":"2014-01-01T00:00:00","Id":2,"Description":"item 2 description"}]}
在客户端,我希望将json反序列化为List<MyType>
(简洁的语言略显松散)
List<MyType> results = HttpResponseMessage.Content.ReadAsAsync<List<MyType>>(new [] { new JsonMediaTypeFormatter () }).Result;
但这会引发异常
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyType]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.<>c__DisplayClass8.<ReadFromStreamAsync>b__6()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
答案 0 :(得分:1)
您的Web API方法返回一个对象,而不是一个列表 - 您试图强制反序列化程序将其重新构建为列表 - 这不会起作用。
您需要:
GetResults()
方法返回列表本身(即将其从MyResponse
更改为List<MyType>
,或者MyResponse
,而不是List<MyType>
。答案 1 :(得分:0)
MyResponse
类是序列化为JSON的类,因此这是调用ReadAsAsync方法时应该使用的类型。
MyResponse responseContent = HttpResponseMessage.Content.ReadAsAsync<MyResponse>(new [] { new JsonMediaTypeFormatter () });
然后,如果您想访问结果列表,请使用responseContent.Results
从我见过的示例中,您也可以省略IEnumerable<MediaTypeFormatter>
参数,因此这也可以。 http://msdn.microsoft.com/en-us/library/hh944541(v=vs.118).aspx
MyResponse responseContent = HttpResponseMessage.Content.ReadAsAsync<MyResponse>();