问题
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;
}

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.
回答1:
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.
回答2:
XmlDeserializeFromString
returns an object
, which does not have a Name
property. You need to either:
- cast it to the type you want to use it as
use the generic method you added which does that:
var thisChannel = XmlDeserializeFromString<Channel>(XMLString);`
- use
dynamic
to resolve the method name at runtime - use reflection to find the
Name
property at runtime
回答3:
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.
.
回答4:
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
来源:https://stackoverflow.com/questions/18444861/how-to-use-deserialized-object