我遇到了将JSON转换为强类型类的错误。
我的JSON:{"listBoxID":"ctl00_ctl00_MainContentRoot_MainContent_lstBxSettings","sourceItemText":"Horizontal Bar","sourceItemValue":"Horizontal"}
DroppedItem droppedItem = JsonConvert.DeserializeObject<DroppedItem>(json);
/// <summary>
/// Outlines an object which is useful in simplifying how a CormantRadDock is created.
/// Instead of passing in lots of parameters, would rather just pass in an object that the
/// CormantRadDock knows how to interpret.
/// </summary>
[DataContract]
public class DroppedItem
{
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
[DataMember(Name = "sourceItemText")]
public string Text { get; set; }
[DataMember(Name = "sourceItemValue")]
public string Value { get; set; }
[DataMember(Name = "listBoxID")]
public Reports ReportType { get; set; }
public DroppedItem() { }
public DroppedItem(string text, string value, string listBoxID)
{
Logger.DebugFormat("Text: {0}, Value: {1}, slidingPaneTitle: {2}", text, value, listBoxID);
Text = text;
Value = value;
ReportType = DetermineReportType(listBoxID);
}
private Reports DetermineReportType(string listBoxID)
{
if (listBoxID.Contains("lstBxHistorical"))
{
return Reports.HistoricalReport;
}
else if (listBoxID.Contains("lstBxCustom"))
{
return Reports.CustomReport;
}
else
{
return Reports.None;
}
}
}
问题在于将listBoxID转换为ReportType。
未捕获Sys.WebForms.PageRequestManagerServerErrorException:Sys.WebForms.PageRequestManagerServerErrorException:将值“ctl00_ctl00_MainContentRoot_MainContent_lstBxSettings”转换为类型'CableSolve.Web.Reports'时出错
无论if语句是找到命中还是默认为else块,都会发生这种情况。如果我不尝试传递listBoxID参数,则不会发生这种情况。
我在这里遗漏了一些东西。我的DataMember名称没有做任何事吗?我以为他们会将listBoxID映射到正确的属性。
答案 0 :(得分:2)
改为这样:
public Reports ReportType { get; set; }
[DataMember(Name = "listBoxID")]
public string listBoxID
{
set
{
ReportType = DetermineReportType(value);
}
}
因为基本上,您可以在没有辅助方法的情况下将string
转换为Report
。在反序列化