【发布时间】:2020-03-09 04:03:41
【问题描述】:
我创建了一个包含多态值的字典,其中保存了一个类对象。我已成功序列化 JSON。但我无法反序列化它。它给出了以下错误:
元素 ':Value' 包含 ':Sale' 数据合约的数据。反序列化器不知道任何映射到该合约的类型。
如果将 JSON 属性 "__type" 替换为 "type",则它可以工作,但无法恢复正确的对象类型。在序列化之前,它包含我的类类型的对象,但在反序列化之后,它包含 system.object。
我的代码如下:
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;
}
}
【问题讨论】:
标签: c# .net types polymorphism datacontractjsonserializer