【问题标题】:JSON to C# object using Data Contracts - What am I missing here?使用数据合同的 JSON 到 C# 对象 - 我在这里缺少什么?
【发布时间】:2011-07-12 17:23:01
【问题描述】:

我在将 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 映射到正确的属性。

【问题讨论】:

    标签: c# json datacontract


    【解决方案1】:

    改成这样:

    public Reports ReportType { get; set; }
    
    
    [DataMember(Name = "listBoxID")]
    public string listBoxID 
    {
        set
        {
             ReportType = DetermineReportType(value);
        } 
    

    }

    因为基本上,您可以将 string 转换为 Report 而无需使用辅助方法。反序列化时未调用构造函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 2010-12-24
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多