【发布时间】:2014-03-26 21:12:23
【问题描述】:
我有一个 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()
对于Results包含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)
【问题讨论】:
-
详细错误信息的哪一部分你不明白?对象不是数组。
-
json长什么样子,MyType类的属性是什么?
-
感谢@BateTech 的回复,我用附加信息修改了我的帖子。
标签: c# json web-services asp.net-web-api deserialization