2

I am experiencing an error converting JSON to a strongly-typed class.

My 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;
        }
    }
}

The issue is with converting listBoxID to ReportType.

Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Error converting value "ctl00_ctl00_MainContentRoot_MainContent_lstBxSettings" to type 'CableSolve.Web.Reports'

It occurs regardless of whether the if statement finds a hit or defaults to the else block. It does not occur if I do not attempt to pass the listBoxID parameter.

I'm missing something here. Are my DataMember names not doing anything? I thought they would map the listBoxID to the correct property.

1 Answer 1

2

Change to something like this:

public Reports ReportType { get; set; }


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

}

Because basically, you can convert that string to a Report without your helper method. The constructor is not being called on deserialization

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.