MVC5 JSON列表NullReference异常

时间:2015-12-03 17:41:34

标签: c# asp.net json nullreferenceexception

我想反序列化一些JSON数据并将其传递给我在ASP.NET MVC 5应用程序中查看。

我的模特:

public class OrderModel
{
    public string Seat { get; set; }
    public string objectId { get; set; }
    public DateTime? createdAt { get; set; }

}

我已经读过要将JSON数据反序列化为对象列表,我必须在这里创建“root”类:

public class OrderRootModel
{
    public List<OrderModel> OrderList { get; set; }

}

这是一个在ApiModel类中获取JSON数据的方法:

//ApiModel class
    public OrderRootModel GetOrderData()
        {

            string url = "https://api.parse.com/1/classes/Orders";

            OrderRootModel model = new OrderRootModel();
            model = JsonConvert.DeserializeObject<OrderRootModel>(getParseIdData(url));
            return model;
        }

我的控制器:

public ActionResult Index()
        {
            ApiModel model = new ApiModel();

            return View(model.GetOrderData()) ;
        }

我的观点(为了测试它几乎是一个空白页面):

@model myCinema.Models.OrderRootModel
@{
    ViewBag.Title = "Index";
    Layout = null;
}

<h2>Order list</h2>

@foreach (var item in Model.OrderList)
{
    @item.objectId;
    @item.createdAt;
    @item.Seat
}

现在启动我的应用程序后,我得到“对象引用未设置为对象的实例”。在“@foreach(Model.OrderList中的var项)”行中。有人可以帮我解决这个问题吗?

修改 要回答为什么我的问题与其他问题不同 - 我明白通常会导致这种异常的原因,但我在代码中明显犯了一个我无法找到的错误,因此我要求你们帮我找到它。我的列表也在根类

我将尽快提供其余的代码和JSON。

EDIT2: 所以在我的GetOrderData中返回线模型似乎是空的。

这是我的api JSON字符串,它来自getParseIdData方法:

{"results":[{"Seat":"5","createdAt":"2015-11-29T18:50:15.320Z","objectId":"BsDSolYPsT","updatedAt":"2015-11-29T19:40:55.020Z"},{"Seat":"6","createdAt":"2015-12-02T22:31:36.892Z","objectId":"kQJ0R5TUvw","updatedAt":"2015-12-02T22:31:36.892Z"},{"Seat":"7","createdAt":"2015-12-02T22:31:40.261Z","objectId":"sVtdj3aipb","updatedAt":"2015-12-02T22:31:40.261Z"},{"Seat":"8","createdAt":"2015-12-02T22:31:43.082Z","objectId":"7oH2ySrDFH","updatedAt":"2015-12-02T22:31:43.082Z"}]}

以下是您要求的方法

public string getParseIdData(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add("X-Parse-Application-Id", id);
        request.Headers.Add("X-Parse-REST-API-KEY", key);
        try
        {
            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            WebResponse errorResponse = ex.Response;
            using (Stream responseStream = errorResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String errorText = reader.ReadToEnd();
                Console.WriteLine(errorText);
            }
            throw;
        }
    }

0 个答案:

没有答案