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

时间:2014-04-04 01:55:37

标签: c# asp.net json json.net restsharp

我遇到了一个我一直在研究的问题,似乎无法弄明白。我试图将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\"]}"

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);

1 个答案:

答案 0 :(得分:2)

尝试将模型更改为

public class MyModel
{
    public int Id { get; set; }
    public List<string> Roles { get; set; }
}

Roles是一个字符串数组。

编辑:进一步检查后,id实际上是一个整数而不是字符串。

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

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

json响应不是一个数组。