![](/img/trans.png)
[英]Cannot deserialize the current JSON object (e.g. {“name”:“value”}) into type 'System.Collections.Generic.IEnumerable`1[WebApplication1.UserInfo]'
[英]C# JSON error => Cannot deserialize JSON object into type 'System.Collections.Generic.IEnumerable`1
我試圖使用Main()
這行代碼訪問.json端點:
var RM= ParseArrayFromWeb<RM>("http://myendpoint.json").ToArray();
這是在MAIN()之上/之外定義的ParseArrayFromWeb
函數
public static IEnumerable<T> ParseArrayFromWeb<T>(string url)
{
var webRequest = WebRequest.Create(url);
using (var response = webRequest.GetResponse())
{
if (response != null)
{
var stream = response.GetResponseStream();
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
return JsonConvert.DeserializeObject<IEnumerable<T>>(reader.ReadToEnd());
}
}
}
throw new WebException("Options request returned null response");
}
}
這是在Main()之上/之外定義的RM類,它應該包含返回的json字段:
public class RM
{
public string calculation_method { get; set; }
public double? related_master_id { get; set; }
public string related_master_name { get; set; }
public string parameter_file_date { get; set; }
public string exchange_complex { get; set; }
public string combined_commodity_code { get; set; }
public string currency { get; set; }
public double? maintenance_margin { get; set; }
public double? scanning_risk { get; set; }
public double? spread_charge { get; set; }
public double? spot_charge { get; set; }
public double? inter_commodity_credit { get; set; }
public double? short_option_minimum { get; set; }
public double? scenario_number { get; set; }
public double? initial_margin { get; set; }
public string exchange_code { get; set; }
public string product_description { get; set; }
public string error_description { get; set; }
}
我得到的錯誤是:
無法將JSON對象反序列化為類型'System.Collections.Generic.IEnumerable`1 [JSON.Program + RM]'。
這里是JSON的一行:
{“error_description”:“error 454”,“combined_commodity_code”:“xx”,“exchange_complex”:“x”,“exchange_code”:“x”,“initial_margin”:null,“maintenance_margin”:null,“scanning_risk”: null,“spread_charge”:null,“spot_charge”:null,“currency”:null,“inter_commodity_credit”:0},
請注意,並非所有字段都存在。 那沒問題。 我必須處理這件事。
有任何想法嗎?
謝謝。
問題在於這條指令:
return JsonConvert.DeserializeObject<IEnumerable<T>>(reader.ReadToEnd());
您不能反序列化接口,因為它們無法實例化,並且反序列化過程本質上實例化對象以將數據存儲在JSON中。 您需要使用具體類進行反序列化,如下所示:
return JsonConvert.DeserializeObject<List<T>>(reader.ReadToEnd());
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.