C#JSON错误=>无法将JSON对象反序列化为类型'System.Collections.Generic.IEnumerable`1

时间:2014-01-27 17:12:58

标签: c# json

我正在尝试使用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]'。

HERE是JSON的一行:

{“error_description”:“错误454”, “combined_commodity_code”: “XX”, “exchange_complex”: “X”, “EXCHANGE_CODE”: “X”, “initial_margin”:空, “maintenance_margin”:空, “scanning_risk”:空, “spread_charge”:空, “spot_charge”:空, “货币”:空” inter_commodity_credit“:0},

请注意,并非所有字段都存在。那没问题。我必须处理它。

有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:3)

问题出在这条指令上:

return JsonConvert.DeserializeObject<IEnumerable<T>>(reader.ReadToEnd());

您无法对接口进行反序列化,因为它们无法实例化,并且反序列化过程本质上会实例化对象以将数据存储在JSON中。您需要使用具体的类进行反序列化,如下所示:

return JsonConvert.DeserializeObject<List<T>>(reader.ReadToEnd());

希望这有帮助。