I'm developing a Windows 10 UWP app and can't seem to get rid of this error: "An exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.ni.dll but was not handled in user code"
I'm using the Rest API to retrieve values from a Data Store on Parse and instantiate objects. Here's what my Class looks like
public class ImageTest
{
public class Image
{
public string __type { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Result
{
public string createdAt { get; set; }
public Image image { get; set; }
public string name { get; set; }
public string objectId { get; set; }
public string updatedAt { get; set; }
}
public class RootObject
{
public List<Result> results { get; set; }
}
}
Here's what my JSON output looks like:
{
"results": [
{
"createdAt": "2015-11-16T02:04:17.403Z",
"image": {
"__type": "File",
"name": "stark.jpg",
"url": "http://xyz.parse.com/stark.jpg"
},
"name": "Stark",
"objectId": "2ypGrvkvg0",
"updatedAt": "2015-11-16T02:04:23.121Z"
},
{
"createdAt": "2015-11-16T02:04:31.409Z",
"image": {
"__type": "File",
"name": "targaryen.jpg",
"url": "http://xyz.parse.com/targaryen.jpg"
},
"name": "Targaryen",
"objectId": "otgO3scX3k",
"updatedAt": "2015-11-16T02:04:40.094Z"
}
]
}
The details of the error message are as follows: Additional information: Element ':image' contains data of the ':File' data contract. The deserializer has no knowledge of any type that maps to this contract. Add the type corresponding to 'File' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.
Your problem is that you are using the
DataContractJsonSerializer
to deserialize your JSON, and"__type"
is a reserved property for this serializer. It is used to identify derived types of polymorphic types. From the docs:Thus you cannot manually add this property to your class and have it translate correctly.
You can, however, leverage the serializer's handling of polymorphism to read and write the
"__type"
automatically, by defining a class hierarchy of image information in which yourImage
type is a subclass of the expected type. Let's rename it toFileImage
for clarity:Now everything should work.
If later you find that server is sending JSON data with additional
"__type"
values and property data (e.g. an embedded Base64 image) you can now easily modify your data model to add additional subclasses toImageBase
.