MrTouch
MrTouch

Reputation: 654

How to use deserialized object?

I am serializing and deserializing an Object in C# for Windows 8 Apps.

I am serializing my Object before passing it to the next View, because passing an object throws out exceptions.

function OnNavigatedTo:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
   base.OnNavigatedTo(e);
   string XMLString = e.Parameter.ToString();
   var thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));
 ....}

Deserializing Function:

  public static Channel XmlDeserializeFromString<Channel>(string objectData)
    {
        return (Channel)XmlDeserializeFromString(objectData, typeof(Channel));
    }

    public static object XmlDeserializeFromString(string objectData, Type type)
    {
        var serializer = new XmlSerializer(type);
        object result;

        using (TextReader reader = new StringReader(objectData))
        {
            result = serializer.Deserialize(reader);
        }

        return result;
    }

Object Content

I want to access the data in this Object, but something like: thisChannel.Name doesn't work. And I don't know how that I can continue working with this Object.

Upvotes: 2

Views: 829

Answers (4)

D Stanley
D Stanley

Reputation: 152556

XmlDeserializeFromString returns an object, which does not have a Name property. You need to either:

  1. cast it to the type you want to use it as
  2. use the generic method you added which does that:

    var thisChannel = XmlDeserializeFromString<Channel>(XMLString);`
    
  3. use dynamic to resolve the method name at runtime
  4. use reflection to find the Name property at runtime

Upvotes: 1

Jon B
Jon B

Reputation: 885

Don't do this.

Passing non-primitive types through a navigation parameter will cause your application to crash when it restores from Suspend.

Only ever pass a primitive type as a navigation parameter in a Windows 8 app.

See SuspensionManager Error when application has more than 1 page in windows 8 XAML/C# app

Upvotes: 0

Farhan Ghumra
Farhan Ghumra

Reputation: 15296

Yes JSON > XML, though you want to stick to XML, use TCD.Serialization, it offers serialization and deserialization XML and JSON to/from stream & string.

.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273244

Start by dropping var in this line:

 //var thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));
 Channel thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));

and then you will at least get an error when the wrong object XmlDeserializeFromString() is selected.

And to be sure you use the right one:

 Channel thisChannel = XmlDeserializeFromString<Channel>(XMLString);

Overloading should be used with care and generally not mixed with Type parameters.

Upvotes: 2

Related Questions