내가 조사한 문제가 있는데 알아낼 수없는 것 같습니다. restsharp 호출에서 API 로의 Json 반환을 역 직렬화하려고합니다. 어레이가 관련되지 않은 첫 번째 제품에서 훌륭하게 작동했습니다. 이제 배열이있는 문자열에서 작업을 시도하고 있으므로 문제가 있습니다. 누군가가 이것을 알아낼 수 있도록 도와 주시면 대단히 감사하겠습니다. 미리 감사드립니다.
그래서 역할을 내 모델에 저장하려고하지만 배열이기 때문에 실패합니다.
내 방법은 다음과 같습니다.
var request = new RestRequest("api/user/{id}", Method.GET);
request.AddUrlSegment("id", id);
var response = client.Execute(request) as RestResponse;
var d = JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
내가 받고있는 오류는 위의 줄에 var d = ...
있습니다. 그것은 말한다 :
Cannot implicitly convert type
'System.Collections.Generic.List<Models.MyModel>' to 'Models.MyModel'
에 대한 응답 var response
은 다음과 같습니다 ( d
모델에 저장하기 위해 저장된 역할 가져 오기 시도 ).
"{\"Id\":22,\"FirstName\":\"Shawn\",\"LastName\":\"John\",\"Roles\":[\"User\"]}"
My MyModel은 다음과 같습니다.
public class MyModel
{
public string Id { get; set; }
public string Roles { get; set; }
}
같은 줄에이 오류가 표시됩니다.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[Models.MyModel]' 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.
모델을 다음과 같이 변경했습니다.
public List<MyModel> Roles { get; set; }
및 컨트롤러 변수 :
List<MyModel> deSerialize2 =
JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
모델을 다음으로 변경해보십시오.
public class MyModel
{
public int Id { get; set; }
public List<string> Roles { get; set; }
}
역할은 문자열의 배열입니다.
편집 : 추가 검사 후 id는 실제로 문자열이 아닌 정수입니다.
또한 deserialize 호출을 이것으로 변경하십시오.
var d = JsonConvert.DeserializeObject<MyModel>(response.Content);
json 응답은 배열이 아닙니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다