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)
MyResponse
클래스는이 ReadAsAsync 메소드를 호출 할 때 사용되어야하는 유형이 있으므로, JSON으로 직렬화지고 것입니다.
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>();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다