繁体   English   中英

使用C#ASP.NET中的RestSharp和JSON.Net反序列化json数组

[英]Deserialize json array using RestSharp and JSON.Net in C# ASP.NET

我有一个问题,我一直在研究,似乎无法搞清楚。 我试图将Json从restsharp调用返回到api。 它在我的第一个没有涉及阵列的情况下工作得很好。 既然我正在尝试在带有数组的字符串上进行,我就遇到了问题。 如果有人能帮我解决这个问题,我将不胜感激,谢谢你提前。

所以我试图将Roles存储到我的模型中,但它失败了,因为它是一个数组:

这是我的方法:

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\"]}"

我的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实际上是一个整数而不是字符串。

此外,将您的反序列化调用更改为此

var d = JsonConvert.DeserializeObject<MyModel>(response.Content);

json响应不是数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM