开发者

Determining what type of object JSON can deserialize into?

开发者 https://www.devze.com 2023-03-21 07:37 出处:网络
I am passing some JSON back from client-side to server-side. if (historicalJSONAttributes != null) { $find(ajaxManagerID).ajaxRequestWithTarget(radDock.get_uniqueID(), $.toJSON(historicalJSONAttribu

I am passing some JSON back from client-side to server-side.

if (historicalJSONAttributes != null) {
    $find(ajaxManagerID).ajaxRequestWithTarget(radDock.get_uniqueID(), $.toJSON(historicalJSONAttributes));
}

or

if (customJSONAttributes!= null) {
    $find(ajaxManagerID).ajaxRequestWithTarget(radDock.get_uniqueID(), $.toJSON(customJSONAttributes));
}

At this point in time RadDock is not structured such that there are derived classes expecting only a historicalJSONAttribute or a customJSONAttribute. The data being given to RadDock is reflective of content it is holding. I did not see a reason (yet?) to structure a parent control around its possible content.

This leaves me with the following issue, however, inside of my RadDock class:

public void RaisePostBackEvent(string eventArgument)
{
    HandleDialogClose(eventArgument);
}

private void HandleDialogClose(string json)
{
    JsonConvert.DeserializeObject<HistoricalLocalSettingsJSON>(json);
}

I have no guarantee that the json data passed to HandleDialogClose is HistoricalLocalSettingsJSON. Should I be pre-prending my eventArgument with a flag to indicate which type of data it is? Is there a better option without a complete restructure?

Thanks

My Classes:

[DataContract]
public class HistoricalLocalSettingsJSON
{
    private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public HistoricalLocalSettingsJSON() { }

    public HistoricalLocalSettingsJSON(string commandName, string dockID, string refreshEnabled, string refreshInterval, string chartType, string timeRestrictionEnabled, string timeStart, string timeEnd, string dataPointsEnabled)
    {
        Logger.InfoFormat("Command Name: {0}, DockID: {1}, RefreshEnabled: {2}, RefreshInterval: {3}, ChartType: {4}, TimeRestrictionEnabled: {5}, TimeStart: {6}, TimeEnd: {7}, DataPointsEnabled: {8}",
            commandName, dockID, refreshEnabled, refreshInterval, chartType, timeRestrictionEnabled, timeStart, timeEnd, dataPointsEnabled);

        CommandName = commandName;
        DockID = dockID;
        RefreshEnabled = bool.Parse(refreshEnabled);
        RefreshInterval = int.Parse(refreshInterval);
        ChartType = (Charts)Enum.Parse(typeof(Charts), chartType);
        TimeRestrictionEnabled = bool.Parse(timeRestrictionEnabled);
        TimeStart = timeStart;
        TimeEnd = timeEnd;
        DataPointsEnabled = !string.IsNullOrEmpty(dataPointsEnabled) ? bool.Parse(dataPointsEnabled) : false;
    }

    [DataMember(Name = "CommandName")]
    public string CommandName { get; set; }

    [DataMember(Name = "DockID")]
    public string DockID { get; set; }

    [DataMember(Name = "RefreshEnabled")]
    public bool RefreshEnabled { get; set; }

    [DataMember(Name = "RefreshInterval")]
    public int RefreshInterval { get; set; }

    [DataMember(Name = "ChartType")]
    public Charts ChartType { get; set; }

    [DataMember(Name = "TimeRestrictionEnabled")]
    public bool TimeRestrictionEnabled { get; set; }

    [DataMember(Name = "TimeStart")]
    public string TimeStart { get; set; }

    [DataMember(Name = "TimeEnd")]
    public string TimeEnd { get; set; }

    [DataMember(Name = "开发者_如何学运维DataPointsEnabled")]
    public bool DataPointsEnabled { get; set; }
}

[DataContract]
public class CustomLocalSettingsJSON
{
    private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public CustomLocalSettingsJSON() { }

    public CustomLocalSettingsJSON(string commandName, string dockID, string refreshEnabled, string refreshInterval, string chartType)
    {
        Logger.InfoFormat("Command Name: {0}, DockID: {1}, RefreshEnabled: {2}, RefreshInterval: {3}, ChartType: {4}",
            commandName, dockID, refreshEnabled, refreshInterval, chartType);

        CommandName = commandName;
        DockID = dockID;
        RefreshEnabled = bool.Parse(refreshEnabled);
        RefreshInterval = int.Parse(refreshInterval);
        ChartType = (Charts)Enum.Parse(typeof(Charts), chartType);
    }

    [DataMember(Name = "CommandName")]
    public string CommandName { get; set; }

    [DataMember(Name = "DockID")]
    public string DockID { get; set; }

    [DataMember(Name = "RefreshEnabled")]
    public bool RefreshEnabled { get; set; }

    [DataMember(Name = "RefreshInterval")]
    public int RefreshInterval { get; set; }

    [DataMember(Name = "ChartType")]
    public Charts ChartType { get; set; }
}

As it stands CustomLocalSettingsJSON is a sub-section of HistoricalLocalSettingsJSON.


One possibility is to create a superstructure:

class ClientData {
    HistoricalLocalSettingsJSON historicalJSONAttributes;
    CustomLocalSettingsJSON customJSONAttributes;
}

Then just wrap your data in a js object that mimics this, leaving one or the other properties null.

If one of the classes is a subclass of the other, you could also use the NewtonSoft javascript deserializer's Populate method to populate an instance of the derived class. This may not be helpful if you need the object typed properly, but you could just restructure the object model with a single class that has a SubType property or something.

But basically you're going to need to let the deserializer know what to do with the data one way or the other. Short of writing a parser to figure it out in advance, there's no direct way to do this that I know of.

Or you could just pass the name of the object type too..

edit

A general approach that lets you add an informational parameter, but still keeping it under one roof, would be to wrap it into an object with two properties, one to identify the type, then the other which is a string of the JSON data. (That's right - you would serialize it twice - first to a JSON string, then to a JSON string string, so it can be passed as a string rather than a JSON object.)

This lets you deserialize the response consistently, and then decide how to proceed.

class ClientData {
    public string TypeName;
    public string Data;
}

...

ClientData interim = JsonConvert.DeserializeObject<ClientData>(json);
switch(interim.TypeName)  {
    // take the appropriate action for each type
    case "HistoricalLocalSettingsJSON ":
        historical = 
           JsonConvert.DeserializeObject<HistoricalLocalSettingsJSON >(interim.Data);
        break;
    case ...
}


You can wrap the deserializeObject in a try/catch block then catch the specific exception the deserializer throws when it cannot match the json data to the type you want. If you have only two possible types you can then try to deserialize the second one after you have gotten an exception for the first one. I can write a code sample later if my explanation is not clear enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消