![](/img/trans.png)
[英]Deserialize JSON with metadata in C# using json.net/RestSharp
[英]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.