[英]Deserialize json array using RestSharp and JSON.Net in C# ASP.NET
I am having an issue I have been researching and can not seem to figure out. 我有一个问题,我一直在研究,似乎无法搞清楚。 I am trying to deserialize Json return from a restsharp call to an api.
我试图将Json从restsharp调用返回到api。 It worked great on my first one where there was not an array involved.
它在我的第一个没有涉及阵列的情况下工作得很好。 Now that I am trying to do it on a string with an array in it I am having issues.
既然我正在尝试在带有数组的字符串上进行,我就遇到了问题。 If anybody could help me figure this out it would be greatly appreciated, thank you in advance.
如果有人能帮我解决这个问题,我将不胜感激,谢谢你提前。
So I am trying to get Roles to be stored to my Model, but it fails because it is an array: 所以我试图将Roles存储到我的模型中,但它失败了,因为它是一个数组:
Here is my method: 这是我的方法:
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);
The error I am getting is on the above line at var d = ...
. 我得到的错误是在
var d = ...
的上面一行。 It says: 它说:
Cannot implicitly convert type
'System.Collections.Generic.List<Models.MyModel>' to 'Models.MyModel'
The response for var response
is (trying to get Roles stored in d
to store in model): var response
是(尝试将存储在d
角色存储在模型中):
"{\"Id\":22,\"FirstName\":\"Shawn\",\"LastName\":\"John\",\"Roles\":[\"User\"]}"
My MyModel looks like so: 我的MyModel看起来像这样:
public class MyModel
{
public string Id { get; set; }
public string Roles { get; set; }
}
Getting this error now on the same line: 现在在同一行上获取此错误:
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.
Changed model to be : 将模型更改为:
public List<MyModel> Roles { get; set; }
and controller variable to : 和控制器变量:
List<MyModel> deSerialize2 =
JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
try changing your model to 尝试将模型更改为
public class MyModel
{
public int Id { get; set; }
public List<string> Roles { get; set; }
}
Roles is an array of strings. 角色是一个字符串数组。
Edit: After further inspection, id is actually an integer not a string. 编辑:进一步检查后,id实际上是一个整数而不是字符串。
Also, change your deserialize call to this 此外,将您的反序列化调用更改为此
var d = JsonConvert.DeserializeObject<MyModel>(response.Content);
The json response isn't an array. json响应不是数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.