I have created a dictionary with polymorphic values in which I have saved a class object. I have successfully serialized the JSON. But I am unable to deserialize it. It gives below error:
Element ':Value' contains data of the ':Sale' data contract. The deserializer has no knowledge of any type that maps to this contract.
If replace the JSON property "__type"
with "type"
then it works but is unable to recover correct object type. Before serialization it contains an object of my class type but after deserialization it contains a system.object
instead.
My code is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
class Program
{
static void Main(string[] args)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("employee","john");
dict.Add("sale",new Sale(9,5243));
dict.Add("restaurant",new Restaurant("Cheese Cake Factory", "New York"));
// Console.Write(dict["sale"]);
//Code for JSON
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
MemoryStream msObj = new MemoryStream();
js.WriteObject(msObj, dict);
msObj.Position = 0;
StreamReader sr = new StreamReader(msObj);
string json = sr.ReadToEnd();
sr.Close();
msObj.Close();
// Decode the thing
Console.Write(json);
Dictionary<string, object> result = new Dictionary<string, object>();
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<string, object>));
result = serializer.ReadObject(stream) as Dictionary<string, object>;
}
}
}
[DataContract]
[KnownType(typeof(Sale))]
public class Sale
{
[DataMember(Name = "SaleId")]
public int SaleId {get; set;}
[DataMember(Name = "Total")]
public int Total{ get; set;}
public Sale(int saleid, int total)
{
SaleId = saleid;
Total = total;
}
public int getTotal()
{
return Total;
}
}
[DataContract(Name = "Restaurant", Namespace="")]
[KnownType(typeof(Restaurant))]
public class Restaurant
{
[DataMember(EmitDefaultValue = false)]
public string Name {get; set;}
[DataMember(EmitDefaultValue = false)]
public string City{get; set;}
public Restaurant(string name, string city)
{
Name = name;
City = city;
}
}
Fiddle link : https://dotnetfiddle.net/CfQxxV