由于我的上一个问题被标记为重复,我在推荐的链接中找不到答案,我再次提出问题。
我想反序列化一些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数据并将其分配给列表的方法。 此方法可能是一个问题,因为它返回null :
//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;
}
以下是获取JSON字符串的方法:
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;
}
}
这是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 ActionResult Index()
{
ApiModel model = new ApiModel();
return View(model.GetOrderData()) ;
}
所以我可能在GetOrderData()方法的某个地方犯了一个错误,因为它返回null。你能帮我解决这个问题吗?
答案 0 :(得分:2)
根据您的代码,这就是将JSON转换为C#类时C#Class应该是什么样的
{
"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 class Result
{
public string Seat { get; set; }
public string createdAt { get; set; }
public string objectId { get; set; }
public string updatedAt { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}