![](/img/trans.png)
[英]how to read and deserialize json array from Post Request in C# Web Method
[英]How to Deserialize a JSON Array from Web API in UPW C#?
我想連接到 bitbay web api,從那里獲取數據 JSON 並將其保存到文件中。 我的 JSON 看起來像這樣:
{
"status": "Ok",
"items": [
{
"id": "737a2935-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581134890",
"a": "0.00926098",
"r": "29999",
"ty": "Buy"
},
{
"id": "6c4474fa-84c9-11ea-8cdc-0242ac11000e",
"t": "1587581122794",
"a": "0.02475367",
"r": "29999",
"ty": "Buy"
}
]
}
我想從中得到 t,a,r 和 ty。 我有代碼:
public class TradeModel
{
public decimal R { get; set; }
public decimal A { get; set; }
public string Ty { get; set; }
public DateTime T { get; set; }
}
public class TradeItemModel
{
public TradeModel Items { get; set; }
}
public class TradeProcessor
{
public static async Task<TradeModel> LoadTrades( int limit = 1 )
{
string url = "";
if (limit <= 300)
{
url = $"https://api.bitbay.net/rest/trading/transactions/BTC-PLN?limit={ limit }";
}
else
{
}
using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
TradeItemModel trade = await response.Content.ReadAsAsync<TradeItemModel>();
return trade.Items;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
After I run this code I gets an Exception: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'DemoLibrary.TradeModel' because the type requires a JSON object (eg {"name":"value" }) 正確反序列化。 要修復此錯誤,請將 JSON 更改為 JSON object(例如 {"name":"value"})或將實現的反序列化類型接口更改為數組或數組的 ILists 接口(IColle 之類的類型)從 JSON 陣列反序列化。 JsonArrayAttribute 也可以添加到類型中以強制它從 JSON 數組反序列化。 路徑‘項目’,第 1 行,position 24。”
TradeItemModel
class 中的Item
應該是一個集合TradeModel[]
或List<TradeModel>
,您也可以添加Status
來檢查它是 OK 還是 KO:
public class TradeItemModel
{
public string Status { get; set; }
public List<TradeModel> Items { get; set; }
}
您還必須將方法簽名更改為:
public static async Task<List<TradeModel>> LoadTrades( int limit = 1 )
我希望這能夠幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.