【发布时间】:2017-02-01 05:52:22
【问题描述】:
我正在使用 ASP.NET MVC 4 编写一个应用程序,并尝试在我的类型的对象中填充列表。我编写控制台应用程序只是为了尝试这段代码:
using (var webClient = new WebClient())
{
var json = webClient.DownloadString(URL);
var myTypeVariable= new JavaScriptSerializer().Deserialize<MyTypeSummary>(json);
return myTypeVariable;
}
myTypeVariable 是一个类型的对象:
public class MyTypeSummary
{
public int Id { get; set; }
public List<MyType> MyTypeItems{ get; set; }
public DateTime PublicationDate { get; set; }
}
不幸的是,当我在 ASP.NET Index() 操作中使用此代码时,它只正确填充了 DateTime 属性。 MyTypeItems 列表保持为空,与在我的控制台应用程序中执行此操作的效果相反(列表已正确填充)。
我的班级是这样的:
public class MyType
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int Unit { get; set; }
public double Price1{ get; set; }
public double Price2{ get; set; }
public double Price3{ get; set; }
}
而且我不明白为什么在控制台应用程序中它运行良好,而在 asp 中根本不起作用。任何人都可以帮忙吗? 编辑:这是我得到的 json 字符串:
"{\"publicationDate\":\"2016-09-23T11:36:26.4723947Z\",\"items\":[{\"name\":\"US Dollar\",\"code\":\"USD\",\"unit\":1,\"purchasePrice\":3.6682,\"sellPrice\":3.6779,\"averagePrice\":3.6730},{\"name\":\"Euro\",\"code\":\"EUR\",\"unit\":1,\"purchasePrice\":3.8842,\"sellPrice\":3.9027,\"averagePrice\":3.8935},{\"name\":\"Swiss Franc\",\"code\":\"CHF\",\"unit\":1,\"purchasePrice\":3.7940,\"sellPrice\":3.8041,\"averagePrice\":3.7990},{\"name\":\"Russian ruble\",\"code\":\"RUB\",\"unit\":100,\"purchasePrice\":6.8865,\"sellPrice\":6.9096,\"averagePrice\":6.8981},{\"name\":\"Czech koruna\",\"code\":\"CZK\",\"unit\":100,\"purchasePrice\":13.9250,\"sellPrice\":13.9584,\"averagePrice\":13.9417},{\"name\":\"Pound sterling\",\"code\":\"GBP\",\"unit\":1,\"purchasePrice\":5.6786,\"sellPrice\":5.6989,\"averagePrice\":5.6887}]}"
【问题讨论】:
-
.Deserialize<MyTypeSummary> -
@StephenMuecke 请原谅我在帖子中的错误,事实上我是在反序列化 MyTypeSummary 而不是 MyType,因为我首先写的。还有其他想法吗?
-
ASP.NET 没有什么特别之处。你确定json字符串没问题吗?请张贴输入
-
@PanagiotisKanavos 已发布。我可以保持原样还是让它更具可读性?
-
尝试用
public List<MyType> items替换public List<MyType> MyTypeItems
标签: c# asp.net json asp.net-mvc deserialization